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 EquipmentHistoryController : Controller {
        private readonly ILogger<EquipmentHistoryController> _logger;
        private readonly FMSContext _context;
        private readonly EquipmentService _service;
        private readonly EquipmentHistoryService _historyService;
        private readonly StorageHelper _storage;

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

        /// <summary>
        /// 공기구 등록 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult AddStockList([FromQuery] PagingRequest req) {
            return List(req, 1);
        }

        /// <summary>
        /// 공기구 대여 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult RentList([FromQuery] PagingRequest req) {
            return List(req, 2);
        }

        /// <summary>
        /// 공기구 반납/손실 목록
        /// </summary>
        [HttpGet("[action]")]
        public IActionResult ReturnList([FromQuery] PagingRequest req) {
            return List(req, 3);
        }

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

            if (stateType != null) {
                if (stateType == 2) { // 대여 
                    query = query.Where(x => x.EquipmentStateTypeId != 1 && x.IsReturned == false);
                } else if (stateType == 3) {
                    query = query.Where(x => x.EquipmentStateTypeId == 3 || x.EquipmentStateTypeId == 4 || x.EquipmentStateTypeId == 5);
                } else {
                    query = query.Where(x => x.EquipmentStateTypeId == stateType);
                }
            } else {
                if (!_context.SiteConfig.Single().UseEquipmentRent) {
                    query = query.Where(x => x.EquipmentStateTypeId != 2);
                }
            }

            var list = _ListSelect(query);

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


        /// <summary>
        /// 조회
        /// </summary>
        /// <param name="siteId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{siteId}/{id}")]
        public IActionResult Get(int siteId, int id) {
            var data = _historyService.Gets(id, siteId);
            if (data.Count() == 0) {
                return NotFound("공기구정보를 찾을 수 없습니다.");
            }
            var item = data.Select(x => new {
                x.SiteId,
                x.EquipmentId,
                x.EquipmentHistoryId,
                x.EquipmentRentId,
                Site = new {
                    x.CmSite.Name,
                },
                EquipmentStateType = new {
                    x.EquipmentStateType.Name
                },
                RentInfo = new {
                    Title = x.FmsEquipmentRentInfo.Title,
                    RentUserName = x.FmsEquipmentRentInfo.RentUserName,
                    RentDate = x.FmsEquipmentRentInfo.RentDate,
                    ReturnDueDate = x.FmsEquipmentRentInfo.ReturnDueDate,
                    ReturnFixDate = x.FmsEquipmentRentInfo.ReturnFixDate
                },
                EquipmentInfo = new {
                    x.FmsEquipment.Name,
                    Standard = x.FmsEquipment.Standard,
                },
                EquipmentName = x.FmsEquipment.Name,
                x.RentCount,
                x.CurrentRentCount,
                x.LossCount,
                x.ReturnCount,
                x.ReturnReason,
                x.IsReturnApproval,
                x.ReturnApprovalDate,
                ReturnApprovalUser = x.CmUser.Name,
                CmFile = _storage.ParseFile(x.CmFile),
            });

            return Ok(item.First());
        }

        /// <summary>
        /// 등록
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Create([FromBody] FmsEquipmentHistory data) {
            if (ModelState.IsValid) {
                _historyService.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.DeleteHistory(id, siteId);

            return Ok();
        }

        // 셀렉트 공통
        private dynamic _ListSelect(IQueryable<FmsEquipmentHistory> query) {
            var list = query.Select(x => new {
                x.EquipmentHistoryId,
                x.EquipmentId,
                x.EquipmentStateTypeId,
                EquipmentStateTypeName = x.EquipmentStateType.Name,
                x.SiteId,
                SiteName = x.CmSite.Name,
                x.FmsEquipment.EquipmentTypeId,
                EquipmentTypeName = x.FmsEquipment.FmsEquipmentCodeType.Name,
                x.FmsEquipment.Name,
                x.FmsEquipment.Standard,
                x.FmsEquipment.Unit,
                x.FmsEquipment.WarehouseId,
                WarehouseName = x.FmsEquipment.FmsMaterialWarehouse.Name,
                x.TotalStockCount,
                x.CurrentRentCount,
                x.CurrentStockCount,
                x.StoredCount,
                x.RentCount,
                x.ReturnCount,
                x.LossCount,
                x.ReturnReason,
                x.AddDate,
                x.EquipmentRentId,
                x.FmsEquipmentRentInfo.RentDate,
                x.FmsEquipmentRentInfo.ReturnDueDate,
                x.FmsEquipmentRentInfo.ReturnFixDate,
                x.FmsEquipment.SupplierName,
                x.FmsEquipment.SupplierPhoneNo,
                RentUserName = x.FmsEquipmentRentInfo.RentUserName,
                x.FmsEquipmentRentInfo.RentUserId,
                ReturnApprovalUserName = x.ReturnApprovalUserId != null ? x.CmUser.Name : "",
                x.ReturnApprovalDate,
            });
            return list;
        }

        // 검색 & 정렬 공통
        private IQueryable<FmsEquipmentHistory> _FilterAndSort(PagingRequest req, int? stateType) {
            var query = _service.GetHistory();

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

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

            if (Util.IsNullOrEmpty(stateType)) {
                // 고정정렬 (사옥 준공순)
                var sortQuery = query.OrderBy(x => x.CmSite.SortOrderNo);
                // 추가 정렬
                sortQuery = sortQuery.ThenSort(req.sort);
                return sortQuery;
            } else {
                // 기본 Entity 정렬
                query = query.Sort(req.sort);
                return query;
            }
        }

    }
}