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.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using FMSAdmin.Helpers;
using System.Data;
using System.IO;
using System.Collections.Generic;
using OfficeOpenXml;

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

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


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

            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);
        }


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

            var list = query.Select(x => new {
                x.FacilityClassId,
                x.ParentFacilityClassId,
                x.Depth,
                x.Name,
                x.Abbreviation,
                x.IsUse
            });
            return list;
        }

        private void ExcelHeaderError() {
            throw new Exception("엑셀 형식이 일치하지 않습니다");
        }


        [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<FmsFacilityCodeClass> list = new List<FmsFacilityCodeClass>();
            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.FmsFacilityCodeClass.Where(x => x.IsUse == true && x.Name == class1 && x.ParentFacilityClassId == null).Select(x => x.FacilityClassId).SingleOrDefault();
                        var classId2 = _context.FmsFacilityCodeClass.Where(x => x.IsUse == true && x.ParentFacilityClassId == classId1 && x.Name == class2).Select(x => x.FacilityClassId).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 facilityCodeClass = new FmsFacilityCodeClass();
                        facilityCodeClass = new FmsFacilityCodeClass {
                            Depth = depth,
                            Name = name,
                            IsUse = true,
                            ExcelRowNum = i
                        };

                        if (depth == 1) {
                            if (classId1 != 0) {
                                facilityCodeClass.ParentFacilityClassId = classId1;
                            } else {
                                facilityCodeClass.FmsFacilityCodeClass2 = new FmsFacilityCodeClass {
                                    Depth = 0,
                                    Name = class1,
                                    Abbreviation = rowName,
                                    IsUse = true
                                };
                            }
                        } else if (depth == 2) {
                            if (classId1 != 0 && classId2 != 0) {
                                facilityCodeClass.ParentFacilityClassId = classId2;
                            } else {
                                facilityCodeClass.FmsFacilityCodeClass2 = new FmsFacilityCodeClass {
                                    Depth = 1,
                                    Name = class2,
                                    Abbreviation = rowName,
                                    IsUse = true,
                                    FmsFacilityCodeClass2 = new FmsFacilityCodeClass {
                                        Depth = 0,
                                        Name = class1,
                                        IsUse = true
                                    }
                                };
                            }
                        }

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

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

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

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

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


        /// 엑셀파일 익스포트
        /// </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.FacilityClassId,
                SiteName = "",
                ClassName1 = x.Depth == 0 ? x.Name : x.Depth == 1 ? x.FmsFacilityCodeClass2.Name : x.FmsFacilityCodeClass2.FmsFacilityCodeClass2.Name,
                ClassName2 = x.Depth == 1 ? x.Name : x.Depth == 2 ? x.FmsFacilityCodeClass2.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);
        }


        /// <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.FacilityClassId,
                x.ParentFacilityClassId,
                x.Depth,
                x.Name,
                x.Abbreviation,
                x.IsUse,
            });

            return Ok(list.First());
        }

        /// <summary>
        /// 수정
        /// </summary>
        [HttpPost("{id}")]
        public IActionResult Edit(int id, [FromBody] FmsFacilityCodeClass row) {
            _logger.LogInformation(row.Dump());

            if (id != row.FacilityClassId) {
                return NotFound();
            }

            //ModelState.Remove("Password"); // 이 수정에서는 비밀번호 제외
            if (ModelState.IsValid) {
                try {
                    _service.Save(row);
                } catch (ServiceException ex) {
                    return BadRequest(ex.Message);
                }
            } else {
                foreach (var ms in ModelState.ToArray()) {
                    _logger.LogInformation(ms.Key);
                }
                return BadRequest(ModelState);
            }

            return Ok();
        }

        /// <summary>
        /// 등록
        /// </summary>
        [HttpPut]
        public IActionResult Create([FromBody] FmsFacilityCodeClass row) {
            // if (!User.IsInRole("Admin"))
            //     return Forbid();

            if (ModelState.IsValid) {
                try {
                    _service.Save(row);
                } catch (ServiceException ex) {
                    return BadRequest(ex.Message);
                }
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

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

            return Ok();
        }

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

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

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

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

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

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

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

            return query;
        }

    }
}