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;

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

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

        /// <summary>
        /// 목록
        /// </summary>
        [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);
        }


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

            var list = query.Select(x => new {
                x.PriceCode,
            });
            return list;
        }

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

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

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

            return query;
        }

        [HttpGet("[action]")]
        public IActionResult GetAllPriceType(int fuelTypeId) {
            var list = _context.BemsPriceType.Where(x => x.FuelTypeId == fuelTypeId)
                        .Select(x => new {
                            x.PriceTypeId,
                            x.PriceTypeIdDesc
                        }).ToList();

            return Ok(list);
        }

        [HttpGet("[action]")]
        public IActionResult GetPriceType(int siteId, int fuelTypeId) {
            var query = from x in _context.BemsPriceType
                        join s in _context.BemsSitePrice on new { x.PriceTypeId } equals new { s.PriceTypeId }
                        where s.SiteId == siteId
                        where s.FuelTypeId == fuelTypeId
                        select new {
                            PriceTypeId = x.PriceTypeId,
                            PriceTypeIdDesc = x.PriceTypeIdDesc
                        };

            var list = query.GroupBy(x => new { x.PriceTypeId, x.PriceTypeIdDesc }).Select(x => new { x.Key.PriceTypeId, x.Key.PriceTypeIdDesc }).ToList();

            return Ok(list);
        }

        [HttpGet("[action]")]
        public IActionResult GetPriceCode(int siteId, int fuelTypeId, int priceTypeId) {
            if (priceTypeId == 0) {
                var query = _context.BemsPriceCode.Where(x => x.FuelTypeId == fuelTypeId)
                        .Select(x => new {
                            SiteId = siteId,
                            FuelTypeId = Convert.ToInt16(x.FuelTypeId),
                            PriceTypeId = priceTypeId,
                            PriceCode = x.PriceCode,
                            PriceCodeDesc = x.PriceCodeDesc,
                            UseYn = "Y",
                            IsPriceCode = true
                        });

                return Ok(query);
            } else {
                var query = from x in _context.BemsSitePrice
                            join s in _context.BemsPriceCode on new { x.PriceCode } equals new { s.PriceCode }
                            where x.SiteId == siteId
                            where x.FuelTypeId == fuelTypeId
                            where x.PriceTypeId == priceTypeId
                            select new {
                                SiteId = x.SiteId,
                                FuelTypeId = x.FuelTypeId,
                                PriceTypeId = x.PriceTypeId,
                                PriceCode = x.PriceCode,
                                PriceCodeDesc = s.PriceCodeDesc,
                                UseYn = x.UseYn,
                                IsPriceCode = x.UseYn == "Y" ? true : false
                            };

                return Ok(query);
            }
        }

        /// <summary>
        /// 저장
        /// </summary>
        [HttpPost("{siteId}/{fuelTypeId}/{priceTypeId}")]
        public IActionResult Save(int siteId, int fuelTypeId, string priceTypeId, [FromBody] BemsSitePrice[] data) {
            _logger.LogInformation("Save");
            //_logger.LogInformation(data.Dump());

            if (ModelState.IsValid) {
                _service.Save(siteId, fuelTypeId, Convert.ToInt32(priceTypeId), data);
            } else {
                return BadRequest(ModelState);
            }
            return Ok();
        }

        /// <summary>
        /// 삭제
        /// </summary>
        [HttpDelete("{siteId}/{fuelTypeId}/{priceTypeId}")]
        public IActionResult Delete(int siteId, int fuelTypeId, string priceTypeId) {
            _service.Delete(siteId, fuelTypeId, Convert.ToInt32(priceTypeId));

            return Ok();
        }

        [HttpGet("[action]")]
        public IActionResult GetFuelType() {
            var query = _service.GetFuelType();

            var list = query.Select(x => new {
                x.FuelTypeId,
                x.Name
            }).ToList();

            return Ok(list);
        }
    }
}