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

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

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using FMSAdmin.Helpers;
using System.Data;
using System.IO;
using OfficeOpenXml;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Collections;

namespace FMSAdmin.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/[controller]")]

    public class FacilityStateController : Controller {
        private readonly ILogger<FacilityStateController> _logger;
        private readonly FMSContext _context;
        private readonly FacilityStateService _service;
        private readonly StorageHelper _storage;
        public FacilityStateController(
            ILogger<FacilityStateController> logger,
            FMSContext context,
            FacilityStateService service,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _service = service;
            _storage = storage;
        }

        /// <summary>
        /// 목록
        /// </summary>
        [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);
        }

        [HttpGet("{id}")]
        public IActionResult Get(int id) {
            var data = _service.Get(id);
            if (data.Count() == 0) {
                return NotFound("정보를 찾을 수 없습니다.");
            }

            DateTime dt = DateTime.Today;
            var list = data.Select(x => new {
                x.FacilityStateId,
                x.Title,
                x.StartDate,
                x.EndDate,
                x.Note,
                StateType = x.StartDate > dt ? 1 : (x.StartDate <= dt && x.EndDate >= dt ? 2 : 3),
                StateTypeName = x.StartDate > dt ? "준비중" : (x.StartDate <= dt && x.EndDate >= dt ? "진행중" : "완료"),
                FmsFacilityStateDetailList = x.FmsFacilityStateDetail.Select(f => new {
                    rownum = f.Type == 1 ? f.QuestionId.ToString() : f.CmSite.Name,
                    f.FacilityStateDetailId,
                    f.FacilityStateId,
                    f.QuestionId,
                    f.Type,
                    f.SiteId,
                    SiteName = f.CmSite.Name,
                    SiteSort = f.CmSite.SortOrderNo,
                    f.Content,
                }).OrderBy(f => f.QuestionId).ThenBy(f => f.Type).ThenBy(f => f.SiteSort).ToList(),
            });

            return Ok(list.First());
        }

        [HttpGet("{id}/{siteId}")]
        public IActionResult GetReply(int id, int siteId) {
            var data = _service.Get(id);
            if (data.Count() == 0) {
                return NotFound("정보를 찾을 수 없습니다.");
            }

            DateTime dt = DateTime.Today;
            var list = data.Select(x => new {
                x.FacilityStateId,
                x.Title,
                x.StartDate,
                x.EndDate,
                x.Note,
                StateType = x.StartDate > dt ? 1 : (x.StartDate <= dt && x.EndDate >= dt ? 2 : 3),
                StateTypeName = x.StartDate > dt ? "준비중" : (x.StartDate <= dt && x.EndDate >= dt ? "진행중" : "완료"),
                FmsFacilityStateDetailList = x.FmsFacilityStateDetail.Where(f => f.Type == 1 || (f.Type == 2 && f.SiteId == siteId)).Select(f => new {
                    rownum = f.Type == 1 ? f.QuestionId.ToString() : "답변",
                    f.FacilityStateDetailId,
                    f.FacilityStateId,
                    f.QuestionId,
                    f.Type,
                    f.SiteId,
                    SiteName = f.CmSite.Name,
                    SiteSort = f.CmSite.SortOrderNo,
                    f.Content,
                }).OrderBy(f => f.QuestionId).ThenBy(f => f.Type).ThenBy(f => f.SiteSort).ToList(),
            });

            return Ok(list.First());
        }

        /// <summary>
        /// 엑셀파일 익스포트
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpGet("excel")]
        public IActionResult ExportExcel([FromQuery] PagingRequest req, string filename) {
            int id = 0;
            if (req.conditions != null) {
                foreach (var item in req.conditions) {
                    if (item.field == "FamilityStateId") {
                        id = Util.ToInt(item.value);
                        break;
                    }
                }
            }
            var query = _service.GetDetail(id);
            query = query.OrderBy(x => x.QuestionId).ThenBy(x => x.Type).ThenBy(x => x.CmSite.SortOrderNo);
            var list = query.Select(x => new {
                rownum = x.Type == 1 ? x.QuestionId.ToString() : x.CmSite.Name,
                x.FacilityStateDetailId,
                x.FacilityStateId,
                x.QuestionId,
                x.Type,
                x.SiteId,
                SiteName = x.CmSite.Name,
                x.Content,
            });

            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 != null ? req.sort.order.ToLower() == "asc" : true, filename);
                }

                package.Save();
            }
            stream.Position = 0;
            string excelName = $"excel-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";
            return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName);
        }

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

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

        /// <summary>
        /// 수정
        /// </summary>
        [HttpPost("{id}")]
        public IActionResult Edit(int id, [FromBody] FmsFacilityState data) {
            if (id != data.FacilityStateId) {
                return BadRequest("잘못된 접근입니다.");
            }

            if (ModelState.IsValid) {
                _service.Edit(id, data);
            } else {
                return BadRequest(ModelState);
            }

            return Ok();
        }

        /// <summary>
        /// 답변
        /// </summary>
        [HttpPost("{id}/{siteId}")]
        public IActionResult Reply(int id, int siteId, [FromBody] FmsFacilityState data) {
            if (id != data.FacilityStateId) {
                return BadRequest("잘못된 접근입니다.");
            }

            if (ModelState.IsValid) {
                _service.Reply(id, siteId, data);
            } else {
                return BadRequest(ModelState);
            }

            return Ok();
        }

        /// <summary>
        /// 삭제
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public IActionResult Delete(int id) {
            _service.Delete(id);

            return Ok();
        }

        private dynamic _ListSelect(IQueryable<FmsFacilityState> query) {
            DateTime dt = DateTime.Today;

            var list = query.Select(x => new {
                x.FacilityStateId,
                x.Title,
                StartDate = x.StartDate.ToString("yyyy-MM-dd"),
                EndDate = x.EndDate.ToString("yyyy-MM-dd"),
                StateType = x.StartDate > dt ? 1 : (x.StartDate <= dt && x.EndDate >= dt ? 2 : 3),
                StateTypeName = x.StartDate > dt ? "준비중" : (x.StartDate <= dt && x.EndDate >= dt ? "진행중" : "완료"),
            });
            return list;
        }

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

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

            //진행상태 검색
            if (req.conditions != null) {
                foreach (var item in req.conditions) {
                    if (item.field == "StateType") {
                        DateTime dt = DateTime.Today;
                        if (item.value == "1") {
                            query = query.Where(x => x.StartDate > dt);
                        } else if (item.value == "2") {
                            query = query.Where(x => x.StartDate <= dt && x.EndDate >= dt);
                        } else if (item.value == "3") {
                            query = query.Where(x => x.EndDate < dt);
                        }
                    }
                }
            }

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

            return query;
        }

    }
}