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

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

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using FMSAdmin.Helpers;
using System.Data;
using System.IO;
using OfficeOpenXml;

namespace FMSApp.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/app/[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>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string siteId) {
            var query = _FilterAndSort(req);
            if (!string.IsNullOrEmpty(siteId)) {
                query = query.Where(x => x.SiteId == Util.ToInt(siteId));
            }
            var list = _ListSelect(query);

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

        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] int siteId, [FromQuery] int contractId) {
            var data = _service.Gets(contractId, siteId);
            if (data.Count() == 0) {
                return NotFound("정보를 찾을 수 없습니다.");
            }
            var item = data.Select(x => new {
                x.PartnerId,
                PartnerName = x.CmPartner.Name,
                x.PartnerTypeId,
                PartnerTypeName = x.PartnerType.Name,
                x.SiteId,
                x.Name,
                x.ContractDate,
                x.StartDate,
                x.EndDate,
                x.OwnerShipName,
                x.OwnerShipPhoneNo,
                x.CommitmentMan,
                x.ContractClassId,
                ContractClassName = x.FmsContractClass.Name,
                x.PaymentTypeId,
                PaymentTypeName = x.FmsPaymentType.Name,
                x.ContractTypeId,
                ContractTypeName = x.FmsContractType.Name,
                x.ContractMethodId,
                ContractMethodName = x.FmsContractMethod.Name,
                x.Comment,
                x.ContractAmountText,
                x.ContractExeGuaranteeRate,
                x.DefectGuaranteeRate,
                x.DefectGuaranteePeriodText,
                CmFile = _storage.ParseFile(x.CmFile)
                // x.RepresentativeName,
                // x.SalesName,
                // x.PhoneNo,
                // x.SalesPhoneNo,
                // x.FaxNo,
                // x.RegistrationNo,
                // x.HomepageUri,
                // x.Address1,
                // x.Adderss2,
                // x.AddressZip1,
                // x.AddressZip2,
                // x.Note,
                // x.IsUse,
            }).FirstOrDefault();
            return Ok(item);
        }


        /// <summary>
        /// 저장
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public IActionResult Save([FromBody] FmsContract data) {
            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}/{id}")]
        public IActionResult Delete(int siteId, int id) {
            _service.Delete(id, siteId);

            return Ok();
        }

        // 셀렉트 공통
        private dynamic _ListSelect(IQueryable<FmsContract> query) {
            var list = query.Select(x => new {
                x.PartnerId,
                x.PartnerTypeId,
                PartnerTypeName = x.PartnerType.Name,
                PartnerName = x.CmPartner.Name,
                x.SiteId,
                x.Name,
                x.ContractId,
                Dates = new {
                    StartDate = x.StartDate == null ? null : ((DateTime)x.StartDate).ToString("yyyy.MM.dd"),
                    EndDate = x.EndDate == null ? null : ((DateTime)x.EndDate).ToString("yyyy.MM.dd"),
                },
                x.ContractAmountText
            });
            return list;
        }


        // 검색 & 정렬 공통
        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));
            }

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

            return query;
        }
    }
}