using System;
using System.IO;
using System.Linq;
using FMSAdmin.Data;
using FMSAdmin.Entities;
using FMSAdmin.Helpers;
using FMSAdmin.Models;
using FMSAdmin.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using OfficeOpenXml;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

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

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

        /// <summary>
        /// 목록
        /// </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}/{id}")]
        public IActionResult Get(int siteId, int id) {
            var data = _service.Gets(id, siteId);
            if (data.Count() == 0) {
                return NotFound("구매업체 코드 정보를 찾을 수 없습니다.");
            }

            var item = data.Select(x => new {
                x.TradeCompanyId,
                x.SiteId,
                CmSite = new {
                    x.Site.Name,
                },
                x.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(item.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 = $"excel-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";
            return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName);
        }

        [HttpPost]
        [Route("[action]")]
        public IActionResult ImportExcelAdmin(IFormFile excelFile) {
            return (ImportExcel(excelFile, true));
        }

        /// <summary>
        /// 엑셀파일 임포트
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public IActionResult ImportExcel(IFormFile excelFile, bool isAdmin = false) {
            IList<FmsMaterialTradeCompany> list = new List<FmsMaterialTradeCompany>();
            var userInfo = _context.CmUser.Where(x => x.UserId == User.Identity.Name).SingleOrDefault();
            using (ExcelPackage excelPackage = new ExcelPackage(excelFile.OpenReadStream())) {
                var worksheet = excelPackage.Workbook.Worksheets[0];
                int colCnt = isAdmin ? 13 : 12;
                //헤더세팅

                ExcelUploadHepler excelUploadHelper = new ExcelUploadHepler();
                excelUploadHelper.GenerateColumns(worksheet, 1, colCnt);
                for (int i = worksheet.Dimension.Start.Row + 1; i <= worksheet.Dimension.End.Row; i++) {
                    if (!excelUploadHelper.IsRowEmpty(worksheet, i, colCnt)) {
                        var site = isAdmin ? excelUploadHelper.GetValue(worksheet, "사옥(*)", i, true) : "";
                        var registrationNo = excelUploadHelper.GetValue(worksheet, "사업자 번호(*)", i, true);
                        var name = excelUploadHelper.GetValue(worksheet, "회사 명칭(*)", i, true);
                        var representativeName = excelUploadHelper.GetValue(worksheet, "회사 대표", i);
                        var phoneNo = excelUploadHelper.GetValue(worksheet, "대표 번호", i);
                        var faxno = excelUploadHelper.GetValue(worksheet, "팩스 번호", i);
                        var salesName = excelUploadHelper.GetValue(worksheet, "담당자 명", i);
                        var salesPhoneNo = excelUploadHelper.GetValue(worksheet, "담당자 번호", i);
                        var addressZip1 = excelUploadHelper.GetValue(worksheet, "우편 번호", i);
                        var address1 = excelUploadHelper.GetValue(worksheet, "회사 주소", i);
                        var homepageUri = excelUploadHelper.GetValue(worksheet, "홈페이지", i);
                        var note = excelUploadHelper.GetValue(worksheet, "비고", i);
                        var isUse = excelUploadHelper.GetValue(worksheet, "사용여부(*)[사용 or 미사용]", i, true);

                        _logger.LogInformation("site " + site);
                        _logger.LogInformation("codnamee " + name);

                        var rowName = "(" + (i) + "번 행)";

                        var siteId = isAdmin ? _context.CmSite.Where(x => x.Name == site && x.IsUse == true).Select(x => x.SiteId).SingleOrDefault() : userInfo.SiteId;

                        if (isAdmin) excelUploadHelper.EntityIdCheck(siteId, "사옥", rowName);
                        excelUploadHelper.EntityIdCheck(registrationNo, "사업자 번호", rowName);

                        if (!isUse.Equals("사용") && !isUse.Equals("미사용")) throw new Exception($"사용여부를 정확히 입력해야합니다.[사용 or 미사용] {rowName}");

                        var tradeCompany = new FmsMaterialTradeCompany {
                            SiteId = siteId,
                            Name = name,
                            RegistrationNo = registrationNo,
                            RepresentativeName = representativeName,
                            PhoneNo = phoneNo,
                            FaxNo = faxno,
                            SalesName = salesName,
                            SalesPhoneNo = salesPhoneNo,
                            AddressZip1 = addressZip1,
                            Address1 = address1,
                            HomepageUri = homepageUri,
                            Note = note,
                            IsUse = isUse.Equals("미사용") ? false : true,
                            ExcelRowNum = i
                        };

                        //글자수 체크
                        TryValidateModel(tradeCompany);

                        if (!ModelState.IsValid) throw new ServiceException(string.Join(" ",
                                        ModelState.Values
                                        .SelectMany(x => x.Errors)
                                        .Select(x => x.ErrorMessage)) + rowName);

                        //중복체크
                        var overlapRowNum = list.Where(x => x.SiteId == tradeCompany.SiteId
                                                && x.RegistrationNo == tradeCompany.RegistrationNo
                                                && x.Name == tradeCompany.Name).Select(x => x.ExcelRowNum).SingleOrDefault();
                        if (overlapRowNum != 0)
                            throw new ServiceException("파일 내 동일 정보가 존재합니다." + "(" + (overlapRowNum) + "번 행 - " + (i) + "번 행)");

                        list.Add(tradeCompany);
                    }
                }
            }
            if (list.Count > 0) {
                _service.ImportExcel(list);

                return Ok($"엑셀업로드를 성공하였습니다. {list.Count}건의 데이터가 등록되었습니다.");
            } else {
                throw new ServiceException("등록할 데이터가 없습니다.");
            }
        }

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

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

            return Ok();
        }

        /// <summary>
        /// 등록
        /// </summary>
        [HttpPut]
        public IActionResult Create([FromBody] FmsMaterialTradeCompany data) {
            _logger.LogInformation("Create");
            //_logger.LogInformation(data.Dump());

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

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

            return Ok();
        }

        // 셀렉트 공통
        private dynamic _ListSelect(IQueryable<FmsMaterialTradeCompany> query) {
            var list = query.Select(x => new {
                x.SiteId,
                SiteName = x.Site.Name,
                x.TradeCompanyId,
                x.Name,
                x.RepresentativeName,
                x.SalesName,
                x.SalesPhoneNo,
                x.Note,
                IsUse = x.IsUse ? "Y" : "N"
            });
            return list;
        }

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

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

            // 추가 정렬
            sortQuery = sortQuery.ThenSort(req.sort);

            return sortQuery;
        }
    }
}