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;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Collections;

namespace FMSApp.Controllers {
    [Authorize]
    [ApiController]
    [ApiVersion("1")]
    [Route("api/app/[controller]")]
    public class EquipmentController : Controller {
        private readonly ILogger<EquipmentController> _logger;
        private readonly FMSContext _context;
        private readonly EquipmentService _service;
        private readonly StorageHelper _storage;

        public EquipmentController(
            ILogger<EquipmentController> logger,
            FMSContext context,
            EquipmentService service,
            StorageHelper storage
            ) {
            _logger = logger;
            _context = context;
            _service = service;
            _storage = storage;
        }

        /// <summary>
        /// 리스트
        /// </summary>
        /// <param name="req"></param>
        /// <param name="siteId"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req) {
            var query = _FilterAndSort(req);

            var list = _ListSelect(query);

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

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

        /// <summary>
        /// 엑셀파일 임포트
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public IActionResult ImportExcel(IFormFile file) {
            IList<Hashtable> list = new List<Hashtable>();
            using (ExcelPackage excelPackage = new ExcelPackage(file.OpenReadStream())) {
                var worksheet = excelPackage.Workbook.Worksheets[0];
                for (int i = worksheet.Dimension.Start.Row; i <= worksheet.Dimension.End.Row; i++) {

                    var name = worksheet.Cells[i, 1].Value;
                    var rfid = worksheet.Cells[i, 2].Value;
                    var code = worksheet.Cells[i, 3].Value;
                    list.Add(new Hashtable {
                        {"Name", name}
                    });
                }
            }
            //_service.ImportExcel(list);
            //return BadRequest(ex.Message);

            return Ok();
        }

        /// <summary>
        /// 조회
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{siteId}/{id}/{historyId}")]
        public IActionResult Get(int siteId, int id, int historyId) {
            var data = _service.Gets(id, siteId);
            if (data.Count() == 0) {
                return NotFound("공기구정보를 찾을 수 없습니다.");
            }
            var item = data.Select(x => new {
                x.EquipmentId,
                x.EquipmentTypeId,
                FmsEquipmentCodeType = new {
                    x.FmsEquipmentCodeType.Name
                },
                BusinessFieldId = x.FmsMaterialWarehouse.BusinessFieldId,
                BusinessFieldName = x.FmsMaterialWarehouse.CmBusinessField.Name,
                x.WarehouseId,
                FmsMaterialWarehouse = new {
                    x.FmsMaterialWarehouse.Name
                },
                x.SiteId,
                CmSite = new {
                    x.Site.Name,
                },
                ImageFile = _storage.ParseFile(x.ImageFile),
                x.Name,
                x.Standard,
                x.Unit,
                x.SupplierName,
                x.SupplierPhoneNo,
                TotalStockCount = x.FmsEquipmentHistory.Where(x => x.EquipmentHistoryId == historyId).Select(x => x.TotalStockCount).FirstOrDefault(),
                CurrentStockCount = x.FmsEquipmentHistory.Where(x => x.EquipmentHistoryId == historyId).Select(x => x.CurrentStockCount).FirstOrDefault(),
            });

            return Ok(item.First());
        }

        /// <summary>
        /// 조회
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [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.EquipmentId,
                x.EquipmentTypeId,
                EquipmentTypeName = x.FmsEquipmentCodeType.Name,
                x.WarehouseId,
                WarehouseName = x.FmsMaterialWarehouse.Name,
                BusinessFieldId = x.FmsMaterialWarehouse.BusinessFieldId,
                BusinessFieldName = x.FmsMaterialWarehouse.CmBusinessField.Name,
                x.SiteId,
                Site = new {
                    x.Site.Name,
                },
                ImageFile = _storage.ParseFile(x.ImageFile),
                x.Name,
                x.Standard,
                x.Unit,
                x.SupplierName,
                x.SupplierPhoneNo,
            });

            return Ok(item.First());
        }

        /// <summary>
        /// 수정
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="id"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("{siteId}/{id}")]
        public IActionResult Edit(int siteId, int id, [FromBody] FmsEquipment data) {
            if (id != data.EquipmentId) {
                return BadRequest("잘못된 접근입니다.");
            }
            ModelState.Remove("RegisterUserId");
            ModelState.RemoveStartOf("ImageFile");
            if (ModelState.IsValid) {
                _service.Edit(id, siteId, data);
            } else {
                return BadRequest(ModelState);
            }

            return Ok();
        }

        /// <summary>
        /// 등록
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Create([FromBody] FmsEquipment data) {
            ModelState.Remove("RegisterUserId");
            ModelState.RemoveStartOf("ImageFile");
            data.RegisterUserId = User.Identity.Name;
            if (ModelState.IsValid) {
                _service.Create(data);
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

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

            return Ok();
        }

        // 셀렉트 공통
        private dynamic _ListSelect(IQueryable<FmsEquipment> query) {
            var list = query.Select(x => new {
                x.EquipmentId,
                x.SiteId,
                SiteName = x.Site.Name,
                x.EquipmentTypeId,
                EquipmentTypeName = x.FmsEquipmentCodeType.Name,
                x.Name,
                StockCount = x.FmsEquipmentHistory.OrderByDescending(x => x.EquipmentHistoryId).Select(x => x.CurrentStockCount).FirstOrDefault() ?? 0,
                x.AddDate,
                x.Standard,
                x.Unit,
                x.SupplierName,
                x.SupplierPhoneNo,
                x.WarehouseId,
                WarehouseName = x.FmsMaterialWarehouse.Name,
            });
            return list;
        }

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

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

            return query;
        }

    }
}