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

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

        /// <summary>
        /// 협력 업체 유형 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req) {
            var query = _FilterAndSort(req);

            //query = query.Where(x => x.WorkTypeId == workTypeId);

            var list = _ListSelect(query);

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


        private dynamic _ListSelect(IQueryable<CmPartnerType> query) {
            //query = query.Where(x => x.SiteId.Name));

            var list = query.Select(x => new {
                x.PartnerTypeId,
                x.Name,
                IsUse = x.IsUse.GetValueOrDefault() ? "Y" : "N"
            });
            return list;
        }

        /// <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>
        /// 조회
        /// </summary>
        [HttpGet("{id}")]
        public IActionResult Get(int id) {
            var data = _service.Get(id);
            if (data.Count() == 0) {
                return NotFound("코드정보를 찾을 수 없습니다.");
            }
            var list = data.Select(x => new {
                x.PartnerTypeId,
                x.Name,
                x.IsUse,
            });

            return Ok(list.First());
        }

        /// <summary>
        /// 저장
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public IActionResult Save([FromBody] CmPartnerType data) {
            _logger.LogInformation("Save");
            //_logger.LogInformation(data.Dump());

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

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

            return Ok();
        }

        // 검색 & 정렬 공통
        private IQueryable<CmPartnerType> _FilterAndSort(PagingRequest req) {
            var query = _service.GetAll();

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

            query = query.Where(x => !string.IsNullOrEmpty(x.Name));

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

            return query;
        }

    }
}