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

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

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        //public IActionResult List([FromQuery]PagingRequest req, [FromQuery]string siteId, [FromQuery]string depth) {
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string depth) {
            var query = _FilterAndSort(req);

            /*
            if (!string.IsNullOrEmpty(siteId)) {
                query = query.Where(x => x.SiteId == Util.ToInt(siteId));
            }
            */

            if (!string.IsNullOrEmpty(depth)) {
                query = query.Where(x => x.Depth == Util.ToInt(depth));
            }

            var list = _ListSelect(query);

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

        /// <summary>
        /// 조회
        /// </summary>
        //[HttpGet("{siteId}/{id}/{depth}")]
        [HttpGet("{id}/{depth}")]
        public IActionResult Get(int id, int depth) {
            var data = _service.Gets(id, depth);
            if (data.Count() == 0) {
                return NotFound("자재 분류 코드 정보를 찾을 수 없습니다.");
            }

            var item = data.Select(x => new {
                x.MaterialClassId,
                /*
                x.SiteId,
                CmSite = new {
                    x.Site.Name,
                },
                */
                x.ParentMaterialClassId,
                x.Depth,
                x.Name,
                x.Abbreviation,
                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 = query.Select(x => new {
                //x.SiteId,
                x.MaterialClassId,
                //SiteName = x.Site.Name,
                ClassName1 = x.Depth == 0 ? x.Name : x.Depth == 1 ? x.FmsMaterialCodeClass2.Name : x.FmsMaterialCodeClass2.FmsMaterialCodeClass2.Name,
                ClassName2 = x.Depth == 1 ? x.Name : x.Depth == 2 ? x.FmsMaterialCodeClass2.Name : "",
                ClassName3 = x.Depth == 2 ? x.Name : "",
            });

            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<FmsMaterialCodeClass> list = new List<FmsMaterialCodeClass>();
            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 ? 4 : 3;
                //헤더세팅

                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 class1 = excelUploadHelper.GetValue(worksheet, "자재 대분류(*)", i, true);
                        var class2 = excelUploadHelper.GetValue(worksheet, "자재 중분류", i);
                        var class3 = excelUploadHelper.GetValue(worksheet, "자재 소분류", i);
                        //var isUse = excelUploadHelper.GetValue(worksheet, "사용여부(*)[사용 or 미사용]", i, true);

                        //_logger.LogInformation("site " + site);

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

                        //var siteId = isAdmin ? _context.CmSite.Where(x => x.Name == site && x.IsUse == true).Select(x => x.SiteId).SingleOrDefault() : userInfo.SiteId;
                        var classId1 = _context.FmsMaterialCodeClass.Where(x => /*x.SiteId == siteId && */x.IsUse == true && x.Name == class1 && x.ParentMaterialClassId == null).Select(x => x.MaterialClassId).SingleOrDefault();
                        var classId2 = _context.FmsMaterialCodeClass.Where(x => /*x.SiteId == siteId && */x.IsUse == true && x.ParentMaterialClassId == classId1 && x.Name == class2).Select(x => x.MaterialClassId).SingleOrDefault();

                        //if (isAdmin) excelUploadHelper.EntityIdCheck(siteId, "사이트명", rowName);

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

                        var depth = (class2 == "" || class2 == null) ? 0 : (class3 == "" || class3 == null) ? 1 : 2;
                        var name = depth == 0 ? class1 : depth == 1 ? class2 : class3;

                        var materialCodeClass = new FmsMaterialCodeClass();
                        materialCodeClass = new FmsMaterialCodeClass {
                            //SiteId = siteId,
                            Depth = depth,
                            Name = name,
                            IsUse = true,
                            ExcelRowNum = i
                        };

                        if (depth == 1) {
                            if (classId1 != 0) {
                                materialCodeClass.ParentMaterialClassId = classId1;
                            } else {
                                materialCodeClass.FmsMaterialCodeClass2 = new FmsMaterialCodeClass {
                                    //SiteId = siteId,
                                    Depth = 0,
                                    Name = class1,
                                    Abbreviation = rowName,
                                    IsUse = true
                                };
                            }
                        } else if (depth == 2) {
                            if (classId1 != 0 && classId2 != 0) {
                                materialCodeClass.ParentMaterialClassId = classId2;
                            } else {
                                materialCodeClass.FmsMaterialCodeClass2 = new FmsMaterialCodeClass {
                                    //SiteId = siteId,
                                    Depth = 1,
                                    Name = class2,
                                    Abbreviation = rowName,
                                    IsUse = true,
                                    FmsMaterialCodeClass2 = new FmsMaterialCodeClass {
                                        //SiteId = siteId,
                                        Depth = 0,
                                        Name = class1,
                                        IsUse = true
                                    }
                                };
                            }
                        }

                        var check = 0;
                        if (depth == 0) check = _context.FmsMaterialCodeClass.Where(x => /*x.SiteId == siteId && */x.Depth == depth && x.Name == name).Count();
                        else check = _context.FmsMaterialCodeClass.Where(x => /*x.SiteId == siteId && */x.Depth == depth && x.ParentMaterialClassId == materialCodeClass.ParentMaterialClassId && x.Name == name).Count();
                        if (check > 0) {
                            throw new ServiceException("기존 분류코드와 동일 정보가 존재합니다." + rowName);
                        }

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

                        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 == materialCodeClass.SiteId
                                                && */x.ParentMaterialClassId == materialCodeClass.ParentMaterialClassId
                                                && x.Depth == materialCodeClass.Depth
                                                && x.Name == materialCodeClass.Name).Select(x => x.ExcelRowNum).SingleOrDefault();
                        if (overlapRowNum != 0)
                            throw new ServiceException("파일 내 동일 정보가 존재합니다." + "(" + (overlapRowNum) + "번 행 - " + (i) + "번 행)");

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

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

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

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

            return Ok();
        }

        /// <summary>
        /// 등록
        /// </summary>
        [HttpPut]
        public IActionResult Create([FromBody] FmsMaterialCodeClass 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}/{depth}")]
        [HttpDelete("{id}/{depth}")]
        public IActionResult Delete(int id, int depth) {
            _service.Delete(id, depth);

            return Ok();
        }

        // 셀렉트 공통
        private dynamic _ListSelect(IQueryable<FmsMaterialCodeClass> query) {
            var list = query.Select(x => new {
                /*
                x.SiteId,
                SiteName = x.Site.Name,
                */
                x.MaterialClassId,
                x.ParentMaterialClassId,
                x.Depth,
                x.Name,
                x.Abbreviation,
                x.IsUse
            });
            return list;
        }

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

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

            query = query.Where(x => x.IsUse == true);

            /*
            if (req.siteId != null) {
                query = query.Where(x => x.SiteId == Util.ToInt(req.siteId));
            }
            */

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

            return query;
        }

        /// <summary>
        /// 자식 노드 리스트
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("childs/{parentId?}")]
        public IActionResult Childs(int? parentId) {
            var query = _service.GetAll().Where(x => x.ParentMaterialClassId == parentId);

            // 최대 3뎁스
            var list = query.OrderBy(x => x.Name).Select(c => new {
                id = c.MaterialClassId,
                name = c.Name,
                children = c.FmsMaterialCodeClass1.OrderBy(x => x.Name).Select(c1 => new {
                    id = c1.MaterialClassId,
                    name = c1.Name,
                    children = c1.FmsMaterialCodeClass1.OrderBy(x => x.Name).Select(c2 => new {
                        id = c2.MaterialClassId,
                        name = c2.Name,
                    })
                })
            });
            return Ok(list);
        }

    }
}