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

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

        /// <summary>
        /// 함수명 : List 
        /// 기  능 : 데이터 목록(grid 조회)
        /// 작성자 : 신현갑
        /// 작성일 : 2020-02-14
        /// 수정자 : 
        /// 수정일 :
        /// 비  고 :  
        /// </summary>
        /// <param name="req"></param>
        /// <param name="siteId"></param>
        /// <returns></returns>
        [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>
        /// 함수명 : Get 
        /// 기  능 : 데이터 조회(상세 Popup DetailForm 조회)
        /// 작성자 : 신현갑
        /// 작성일 : 2020-02-14
        /// 수정자 : 
        /// 수정일 :
        /// 비  고 : 
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="partnerId"></param>
        /// <returns></returns>
        [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,
                },
                //BusinessFieldName = x.BusinessField.Name,
                //PartnerTypeName = x.PartnerType.Name,
                //컬럼 정렬 순서 변경 2020-05-27 수정
                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>
        /// 함수명 : ExportExcel 
        /// 기  능 : 엑셀 파일 생성(ExportExcel)
        /// 작성자 : 신현갑
        /// 작성일 : 2020-02-14
        /// 수정자 : 
        /// 수정일 :
        /// 비  고 : 
        /// </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>
        /// 함수명 : Create 
        /// 기  능 : 데이터 신규 생성(Create)
        /// 작성자 : 신현갑
        /// 작성일 : 2020-02-14
        /// 수정자 : 
        /// 수정일 :
        /// 비  고 : 
        /// </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>
        /// 함수명 : Edit 
        /// 기  능 : 데이터 수정(Update)
        /// 작성자 : 신현갑
        /// 작성일 : 2020-02-14
        /// 수정자 : 
        /// 수정일 :
        /// 비  고 :   
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="partnerId"></param>
        /// <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>
        /// 함수명 : Delete 
        /// 기  능 : 데이터 삭제(Delete)
        /// 작성자 : 신현갑
        /// 작성일 : 2020-02-14
        /// 수정자 : 
        /// 수정일 :
        /// 비  고 :
        /// </summary>
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="partnerId"></param>
        /// <returns></returns>
        [HttpDelete("{siteId}/{partnerId}")]
        public IActionResult Delete(int siteId, int partnerId) {
            _service.Delete(siteId, partnerId);

            return Ok();
        }

        /// <summary>
        /// 함수명 : _ListSelect 
        /// 기  능 : 셀렉트 공통(grid 조회)
        /// 작성자 : 신현갑
        /// 작성일 : 2020-02-14
        /// 수정자 : 
        /// 수정일 :
        /// 비  고 :
        /// </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.RepresentativeName,
                x.PhoneNo,
                x.FaxNo,
                x.SalesName,
                x.SalesPhoneNo,
                x.RegistrationNo,
                x.AddressZip1,
                x.AddressZip2,
                x.Address1,
                x.Adderss2,
                x.HomepageUri,
                x.Note,
                IsUse = x.IsUse.GetValueOrDefault() ? "Y" : "N",
            });
            return list;
        }

        /// <summary>
        /// 함수명 : _FilterAndSort 
        /// 기  능 : 검색 & 정렬
        /// 작성자 : 신현갑
        /// 작성일 : 2020-02-14
        /// 수정자 : 
        /// 수정일 :
        /// 비  고 :
        /// </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 == 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 == req.siteId);
                query = query.Where(x => x.BusinessFieldId == req.businessFieldId || x.BusinessField.Name == "공통");
            }

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

            // 기본 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;
        }

    }
}