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 ContractManagementController : Controller {
        private readonly ILogger<ContractManagementController> _logger;
        private readonly FMSContext _context;
        private readonly ContractManagementService _service;
        private readonly StorageHelper _storage;

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


        /// <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}/{contractId}")]
        public IActionResult Get(int siteId, int contractId) {
            var data = _service.Get(siteId, contractId);
            if (data.Count() == 0) {
                return NotFound("계약 정보를 찾을 수 없습니다.");
            }
            var list = data.Select(x => new {
                x.ContractId,
                x.SiteId,
                CmSite = new {
                    x.CmSite.Name,
                },
                x.Name,
                x.PartnerTypeId,
                CmPartnerType = new {
                    x.PartnerType.Name
                },
                x.PartnerId,
                CmPartner = new {
                    x.CmPartner.Name
                },
                // ContractDate = x.ContractDate == null ? "" : ((DateTime)x.ContractDate).ToString("yyyy-MM-dd"),
                // StartDate = x.StartDate == null ? "" : ((DateTime)x.StartDate).ToString("yyyy-MM-dd"),
                // EndDate = x.EndDate == null ? "" : ((DateTime)x.EndDate).ToString("yyyy-MM-dd"),

                // ContractDate = x.ContractDate != null ? x.ContractDate.Value.ToString("yyyy/MM/dd") : null,
                // StartDate = x.StartDate != null ? x.StartDate.Value.ToString("yyyy/MM/dd") : null,
                // EndDate = x.EndDate != null ? x.EndDate.Value.ToString("yyyy/MM/dd") : null,

                x.ContractDate,
                x.StartDate,
                x.EndDate,
                x.OwnerShipName,
                x.OwnerShipPhoneNo,
                x.CommitmentMan,
                x.Comment,
                x.ContractClassId,
                FmsContractClass = new {
                    x.FmsContractClass.Name
                },
                x.ContractTypeId,
                FmsContractType = new {
                    x.FmsContractType.Name
                },
                x.ContractMethodId,
                FmsContractMethod = new {
                    x.FmsContractMethod.Name
                },
                x.PaymentTypeId,
                FmsPaymentType = new {
                    x.FmsPaymentType.Name
                },
                //2020-04-13 컬럼 추가
                x.ContractAmountText,
                x.ContractExeGuaranteeRate,
                x.DefectGuaranteeRate,
                x.DefectGuaranteePeriodText,
                x.FileId,
                CmFile = _storage.ParseFile(x.CmFile),

                // CmFile = new {
                //     x.CmFile.Name
                //     x.CmFile.Name
                // },
            });

            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}/{contractId}")]
        public IActionResult Edit(int siteId, int contractId, [FromBody] FmsContract data) {
            if (contractId != data.ContractId) {
                return BadRequest("잘못된 접근입니다.");
            }
            ModelState.RemoveStartOf("CmFile");
            if (ModelState.IsValid) {
                _service.Edit(siteId, contractId, data);
            } else {
                return BadRequest(ModelState);
            }

            return Ok();
        }

        /// <summary>
        /// 신규(Creae)
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Create([FromBody] FmsContract 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}/{contractId}")]
        public IActionResult Delete(int siteId, int contractId) {
            _service.Delete(siteId, contractId);

            return Ok();
        }

        /// <summary>
        /// 셀렉트 공통(_ListSelect)
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private dynamic _ListSelect(IQueryable<FmsContract> query) {
            var list = query.Select(x => new {
                x.ContractId,
                x.SiteId,
                //컬럼 정렬 순서 변경 2020-05-27 수정
                StartDate = x.StartDate != null ? x.StartDate.Value.ToString("yyyy-MM-dd") : null,
                EndDate = x.EndDate != null ? x.EndDate.Value.ToString("yyyy-MM-dd") : null,
                SiteName = x.CmSite.Name,
                x.Name,
                x.PartnerTypeId,
                PartnerTypeName = x.PartnerType.Name,
                FilePath = _storage.getFilePath(x.CmFile),
                FileName = x.CmFile.Name,
                // ContractDate = x.ContractDate == null ? "" : ((DateTime)x.ContractDate).ToString("yyyy-MM-dd"),
                // StartDate = x.StartDate == null ? "" : ((DateTime)x.StartDate).ToString("yyyy-MM-dd"),
                // EndDate = x.EndDate == null ? "" : ((DateTime)x.EndDate).ToString("yyyy-MM-dd"),

                ContractDate = x.ContractDate != null ? x.ContractDate.Value.ToString("yyyy-MM-dd") : null,

                x.PartnerId,
                PartnerName = x.CmPartner.Name,
                // x.ContractDate,
                // x.StartDate,
                // x.EndDate,
                x.OwnerShipName,
                x.OwnerShipPhoneNo,
                x.CommitmentMan,
                x.Comment,
                x.ContractClassId,
                ContractClassName = x.FmsContractClass.Name,
                x.ContractTypeId,
                ContractTypeName = x.FmsContractType.Name,
                x.ContractMethodId,
                ContractMethodName = x.FmsContractMethod.Name,
                x.PaymentTypeId,
                PaymentTypeName = x.FmsPaymentType.Name,
                x.ContractAmountText,
                x.ContractExeGuaranteeRate,
                x.DefectGuaranteeRate,
                x.DefectGuaranteePeriodText,
                x.FileId,
                File = x.CmFile.Name,
            });
            return list;
        }

        /// <summary>
        /// 검색 & 정렬(_FilterAndSort)
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        private IQueryable<FmsContract> _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));
            }

            //정렬 (시작일)
            //query = query.OrderBy(x => x.StartDate);

            //고정정렬 (사옥 준공순)
            //var sortQuery = query.OrderBy(x => x.CmSite.SortOrderNo);

            // 추가 정렬
            // if (req.sort.field == "StoredAndAproval") { // 기본 커스텀 정렬 예제 (입고역순,승인일순)
            //     sortQuery = sortQuery.ThenByDescending(x => x.StoredDate);
            //     sortQuery = sortQuery.ThenBy(x => x.ApprovalDate);
            // } else {
            //     sortQuery = sortQuery.ThenSort(req.sort);
            // }     

            //정렬 (시작일)
            var sortQuery = query.OrderByDescending(x => x.StartDate);

            // 기본 Entity 정렬
            sortQuery = sortQuery.ThenSort(req.sort);

            // 추가 정렬
            // if (req.sort.field == "StoredAndAproval") { // 기본 커스텀 정렬 예제 (입고역순,승인일순)
            //     sortQuery = sortQuery.ThenByDescending(x => x.StoredDate);
            //     sortQuery = sortQuery.ThenBy(x => x.ApprovalDate);
            // } else {
            //     sortQuery = sortQuery.ThenSort(req.sort);
            // }            

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

            return sortQuery;

        }

    }
}