
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 ReportFormatController : Controller {
        private readonly ILogger<ReportFormatController> _logger;
        private readonly FMSContext _context;
        private readonly ReportFormatService _service;

        public ReportFormatController(
            ILogger<ReportFormatController> logger,
            FMSContext context,
            ReportFormatService service

            ) {
            _logger = logger;
            _context = context;
            _service = service;

        }

        /// <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<BemsReportFormat> query) {

            var list = query.Select(x => new {
                x.SiteId,
                SiteName = x.CmSite.Name,
                x.ReportFormatId,
                x.BusinessFieldId,
                BusinessFieldName = x.CmBusinessField.Name,
                x.FormatName
                //Facilitycode= x.BemsReportFormatToFacility.Facilitycode.First(),
            });
            return list;
        }

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

            if (siteId != data.SiteId && id != data.ReportFormatId) {
                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.CmSite.Name,
                },
                x.BusinessFieldId,
                x.FormatName,
                CmBusinessField = new { x.CmBusinessField.Name },
                BemsReportFormatContent = x.BemsReportFormatContent.Select(f => new {
                    f.ContentId,
                    f.Content
                }).ToList(),
                BemsReportFormatToFacility = x.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());
        }


        /// <summary>
        /// 등록
        /// </summary>
        [HttpPut]
        public IActionResult Create([FromBody] BemsReportFormat 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}/{reportFormatId}")]
        public IActionResult Delete(int reportFormatId, int siteId) {
            _service.Delete(reportFormatId, siteId);

            return Ok();
        }

        // 검색 & 정렬 공통
        private IQueryable<BemsReportFormat> _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.businessFieldId != null) {
                query = query.Where(x => x.SiteId == req.siteId);
                query = query.Where(x => x.BusinessFieldId == req.businessFieldId || x.CmBusinessField.Name == "공통");
            }

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

            return query;
        }

    }
}