
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;
using SelectPdf;

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

        public ReportHistoryController(
            ILogger<ReportHistoryController> logger,
            FMSContext context,
            ReportHistoryService 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);

            var list = _ListSelect(query);

            var paging = PagingList.Pagination(list, req.page, req.limit);
            return Ok(paging);
        }


        private dynamic _ListSelect(IQueryable<BemsReportHistory> query) {

            var list = query.Select(x => new {
                x.SiteId,
                x.Seq,
                SiteName = x.BemsReportFormat.CmSite.Name,
                BusinessFieldName = x.BemsReportFormat.CmBusinessField.Name,
                x.ReportName,
                x.CreateDate,
                x.Writer,
                x.Confirm1,
                x.Confirm2,
                x.FileId,
                x.FormatName

            });
            return list;
        }

        /// <summary>
        /// 수정
        /// </summary>
        [HttpPost("{siteId}/{id}")]
        public IActionResult Edit(int siteId, int id, [FromBody] BemsReportHistory data) {
            //_logger.LogInformation(data.Dump());

            if (siteId != data.SiteId && id != data.Seq) {
                return NotFound();
            }

            //ModelState.Remove("Password"); // 이 수정에서는 비밀번호 제외
            if (ModelState.IsValid) {
                _service.Save(data);
            } else {
                foreach (var ms in ModelState.ToArray()) {
                    _logger.LogInformation(ms.Key);
                }
                return BadRequest(ModelState);
            }

            return Ok();
        }

        [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.SiteId,
                CmSite = new {
                    x.BemsReportFormat.CmSite.SiteId,
                    x.BemsReportFormat.CmSite.Name
                },
                CmBusinessField = new {
                    x.BemsReportFormat.CmBusinessField.BusinessFieldId,
                    x.BemsReportFormat.CmBusinessField.Name

                },

                x.ReportName,
                x.ReportFormatId,

                x.FormatName,
                x.Writer,
                CmFile = _storage.ParseFile(x.CmFile),
                ApproverUser1 = x.ApproverUser1 != null ? _storage.ParseFile(x.ApproverUser1.CmFile1) : null,
                ApproverUser2 = x.ApproverUser2 != null ? _storage.ParseFile(x.ApproverUser2.CmFile1) : null,
                x.Confirm1,
                x.Confirm2,
                ApproveDate1 = x.ApproveDate1 != null ? x.ApproveDate1.Value.ToString("yyyy-MM-dd") : "",
                ApproveDate2 = x.ApproveDate2 != null ? x.ApproveDate2.Value.ToString("yyyy-MM-dd") : "",
                BemsReportHistoryContent = x.BemsReportHistoryContent.Select(f => new {
                    f.ContentId,
                    f.Content
                }).ToList(),
                BemsReportFormatToFacility = x.BemsReportFormat.BemsReportFormatToFacility.Select(f => new {
                    f.SiteId,
                    f.ReportFormatId,
                    f.FacilityCode,
                    //CmFacility = new {
                    FacilityName = f.CmFacility.Name,
                    f.CmFacility.BuildingId,
                    CmBuilding = new {
                        f.CmFacility.CmBuilding.Name,
                    },
                    f.CmFacility.FloorId,
                    CmFloor = new {
                        f.CmFacility.CmFloor.Name,
                    },
                    FacilityLoc = f.CmFacility.CmFloor.Name,
                    f.CmFacility.FirstClassId,
                    FirstClassName = f.CmFacility.FmsFacilityCodeClass.Name,
                    f.CmFacility.SecondClassId,
                    SecondClassName = f.CmFacility.FmsFacilityCodeClass1.Name,
                    f.CmFacility.ThirdClassId,
                    ThirdClassName = f.CmFacility.FmsFacilityCodeClass2.Name,
                }).ToList(),
            });

            return Ok(list.First());
        }

        [HttpGet("pdf/{siteId}/{id}")]
        [AllowAnonymous]
        public IActionResult PdfTest(int siteId, int id) {
            var list = _service.Get(id, siteId);
            if (list.Count() == 0) {
                return NotFound("정보를 찾을 수 없습니다.");
            }
            var data = list.FirstOrDefault();
            var contents = data.BemsReportHistoryContent.Select(x => x.Content).ToArray();
            var content = string.Join("", contents);
            HtmlToPdf converter = new HtmlToPdf();
            _logger.LogInformation(content);
            PdfDocument doc = converter.ConvertHtmlString(content);

            string filename = $"ReportHistoryContent_{data.SiteId}_{data.Seq}.pdf";
            var path = _storage.GetLocalPath("/temp/" + filename);
            _logger.LogInformation(path);
            doc.Save(path);
            doc.Close();
            return Redirect("/files/temp/" + filename);
        }


        /// <summary>
        /// 등록
        /// </summary>
        [HttpPut]
        public IActionResult Create([FromBody] BemsReportHistory data) {
            // if (!User.IsInRole("Admin"))
            //     return Forbid();

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

        /// <summary>
        /// 삭제
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{siteId}/{ReportHistoryId}")]
        public IActionResult Delete(int ReportHistoryId, int siteId) {
            _service.Delete(ReportHistoryId, siteId);
            return Ok();
        }


        [HttpGet("[action]")]
        public IActionResult Confirm([FromQuery] int siteId, [FromQuery] int seq, [FromQuery] int type, [FromQuery] string approverUserId, [FromQuery] string approverUserName) {
            var persist = _context.BemsReportHistory.Where(x => x.SiteId == siteId && x.Seq == seq).FirstOrDefault();
            if (type == 1) {
                persist.ApproverUserId1 = approverUserId;
                persist.Confirm1 = approverUserName;
                persist.ApproveDate1 = DateTime.Now;
            }
            if (type == 2) {
                persist.ApproverUserId2 = approverUserId;
                persist.Confirm2 = approverUserName;
                persist.ApproveDate2 = DateTime.Now;
            }
            _context.BemsReportHistory.Update(persist);
            _context.SaveChanges();

            return Ok();

        }

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

            // 기본 Entity 검색
            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));
            }
            // 업무분야 필드가 있는경우만 추가
            if (req.businessFieldId != null) {
                query = query.Where(x => x.SiteId == User.GetSiteId());
                query = query.Where(x => x.BemsReportFormat.BusinessFieldId == req.businessFieldId || x.BemsReportFormat.CmBusinessField.Name == "공통");
            }

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

            return query;
        }

    }
}