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

using FMSAdmin.Data;
using FMSAdmin.Models;
using FMSAdmin.Entities;

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

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

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

        /// <summary>
        /// 셀렉트 공통
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private dynamic _ListSelect(IQueryable<CmInvestigation2History> query) {
            var list = query.Select(x => new {
                x.SiteId,
                x.InvestigationId,
                x.HistoryId,
                x.RevisionNo,
                x.FileId,
                CmFile = _storage.ParseFile(x.CmFile),
                x.Description,
                x.UpdatedDate,
                UpdateUserName = x.CmInvestigation2.IsAllSite ? x.CmUser.CmSite.Name : x.CmUser.Name,
            });
            return list;
        }

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string siteId, [FromQuery] string investigationId) {

            var query = _FilterAndSort(req);
            query = query.Where(x => x.InvestigationId == Util.ToInt(investigationId));
            if (!Util.IsNullOrEmpty(siteId)) {
                var currentUserSiteId = _context.CmUser.Where(x => x.UserId == User.Identity.Name).Select(x => x.SiteId).SingleOrDefault();
                query = query.Where(x => x.CmUser.SiteId == currentUserSiteId || x.CmUser.SiteId == x.CmInvestigation2.SiteId);
            }
            var list = _ListSelect(query);
            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }

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

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

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

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

            return query;
        }

        /// <summary>
        /// 조회
        /// </summary>
        [HttpGet("{siteId}/{investigationId}/{historyId}")]
        public IActionResult Get(int siteId, int investigationId, int historyId) {
            var data = _service.Get(siteId, investigationId, historyId);
            if (data.Count() == 0) {
                return NotFound("정보를 찾을 수 없습니다.");
            }
            var list = data.Select(x => new {
                x.SiteId,
                x.InvestigationId,
                x.HistoryId,
                x.RevisionNo,
                CmUser = new {
                    x.CmUser.Name,
                },
                CmFile = _storage.ParseFile(x.CmFile),
                x.Description
            });
            return Ok(list.First());
        }

        /// <summary>
        /// 조회
        /// </summary>
        [HttpGet("{siteId}/{InvestigationId}")]
        public int GetNextRevisionNo(int siteId, int investigationId) {
            int nextRevisionNo = _service.GetRevisionNo(siteId, investigationId);
            return nextRevisionNo;
        }

        /// <summary>
        /// 등록
        /// </summary>
        [HttpPut]
        public IActionResult Create([FromBody] CmInvestigation2History data) {
            _logger.LogInformation("Create");
            //_logger.LogInformation(data.Dump());

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


        /// <summary>
        /// 수정
        /// </summary>
        [HttpPost("{siteId}/{investigationId}/{historyId}")]
        public IActionResult Edit(int siteId, int investigationId, int historyId, [FromBody] CmInvestigation2History data) {
            _logger.LogInformation("Edit");
            _logger.LogInformation("id:" + historyId);
            _logger.LogInformation("siteId:" + siteId);
            //_logger.LogInformation(data.Dump());
            if (historyId != data.HistoryId) {
                return BadRequest("잘못된 접근입니다.");
            }

            if (ModelState.IsValid) {
                data.UpdatedUserId = User.Identity.Name;
                _service.Edit(data);
            } else {
                return BadRequest(ModelState);
            }

            return Ok();
        }

        /// <summary>
        /// 삭제
        /// </summary>
        // [HttpDelete("{siteId}/{InvestigationId}/{historyId}")]
        // public IActionResult Delete(int siteId, int id) {
        //     _service.Delete(id, siteId);
        //     return Ok();
        // }
    }
}