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;

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

        public LegalCheckPartnerController(
            ILogger<LegalCheckPartnerController> logger,
            FMSContext context,
            LegalCheckPartnerService service
            ) {
            _logger = logger;
            _context = context;
            _service = service;
        }

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

        /// <summary>
        /// 조회
        /// </summary>
        [HttpGet("{siteId}/{partnerId}")]
        public IActionResult Get(int siteId, int partnerId) {
            var data = _service.Get(siteId, partnerId);
            if (data.Count() == 0) {
                return NotFound("법정 검사 기관 정보를 찾을 수 없습니다.");
            }
            var list = data.Select(x => new {
                x.PartnerId,
                x.SiteId,
                CmSite = new {
                    x.CmSite.Name,
                },
                SiteName = x.CmSite.Name,
                x.Name,
                x.PartnerTypeId,
                CmPartnerType = new {
                    x.PartnerType.Name,
                },
                x.BusinessFieldId,
                CmBusinessField = new {
                    x.BusinessField.Name,
                },
                x.RegistrationNo,
                x.RepresentativeName,
                x.PhoneNo,
                x.FaxNo,
                x.SalesName,
                x.SalesPhoneNo,
                x.AddressZip1,
                x.AddressZip2,
                x.Address1,
                x.Adderss2,
                x.HomepageUri,
                x.Note,
                x.IsUse,
            });

            return Ok(list.First());
        }

        /// <summary>
        /// 엑셀파일 익스포트
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpGet("excel")]
        public IActionResult ExportExcel([FromQuery] PagingRequest req, string filename) {
            req.page = 1;
            req.limit = 0;
            var query = _FilterAndSort(req);

            var list = _ListSelect(query);

            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?.order?.ToLower() == "asc", filename);
                }
                package.Save();
            }
            stream.Position = 0;
            string excelName = $"법정검사기관관리-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";
            return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName);
        }

        /// <summary>
        /// 수정(Edit)
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("{siteId}/{partnerId}")]
        public IActionResult Edit(int siteId, int partnerId, [FromBody] CmPartner data) {
            if (partnerId != data.PartnerId) {
                return BadRequest("잘못된 접근입니다.");
            }

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

            return Ok();
        }

        /// <summary>
        /// 신규(Creae)
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Create([FromBody] CmPartner data) {
            _logger.LogInformation("Create");
            //_logger.LogInformation(data.Dump());

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

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

            return Ok();
        }

        /// <summary>
        /// 셀렉트 공통(_ListSelect)
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private dynamic _ListSelect(IQueryable<CmPartner> query) {
            var list = query.Select(x => new {
                x.PartnerId,
                x.SiteId,
                SiteName = x.CmSite.Name,
                x.Name,
                x.BusinessFieldId,
                BusinessFieldName = x.BusinessField.Name,
                x.PartnerTypeId,
                PartnerTypeName = x.PartnerType.Name,
                x.RegistrationNo,
                x.RepresentativeName,
                x.PhoneNo,
                x.FaxNo,
                x.SalesName,
                x.SalesPhoneNo,
                x.AddressZip1,
                x.AddressZip2,
                x.Address1,
                x.Adderss2,
                x.HomepageUri,
                x.Note,
                IsUse = x.IsUse.GetValueOrDefault() ? "Y" : "N",
            });
            return list;
        }

        /// <summary>
        /// 검색 & 정렬(_FilterAndSort)
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        private IQueryable<CmPartner> _FilterAndSort(PagingRequest req) {
            var query = _service.GetAll();

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

            if (req.siteId != null) {
                query = query.Where(x => x.SiteId == req.siteId);
            }


            // 업무분야 필드가 있는경우만 추가
            if (req.businessFieldId != null) {
                query = query.Where(x => x.SiteId == req.siteId);
                query = query.Where(x => x.BusinessFieldId == req.businessFieldId || x.BusinessField.Name == "공통");
            }

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

            return query;
        }

    }
}