using System;
using System.Linq;
using System.Threading.Tasks;

using FMSAdmin.Data;
using FMSAdmin.Models;
using FMSAdmin.Entities;
using FMSApp.Services;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using FMSAdmin.Helpers;
using System.Data;
using System.IO;
using OfficeOpenXml;

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




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

        /// <summary>
        /// 목록
        /// </summary>
        [HttpGet]
        public IActionResult List([FromQuery] PagingRequest req, [FromQuery] string siteId, [FromQuery] bool useServicePartner, bool businessAuth) {
            var query = _FilterAndSort(req);
            query = BusinessFieldHelper.Apply<CmPartner>(_context, User, businessAuth, query);

            if (!string.IsNullOrEmpty(siteId)) {
                query = query.Where(x => x.SiteId == Util.ToInt(siteId));
            }
            if (useServicePartner) {
                query = query.Where(x => x.PartnerType.Name != "용역업체");
            }
            var list = _ListSelect(query);

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

        [HttpGet("[action]")]
        public IActionResult Get([FromQuery] int siteId, [FromQuery] int partnerId) {
            var data = _service.Gets(partnerId, siteId);
            if (data.Count() == 0) {
                return NotFound("정보를 찾을 수 없습니다.");
            }
            var item = data.Select(x => new {
                x.PartnerId,
                x.PartnerTypeId,
                PartnerTypeName = x.PartnerType.Name,
                x.BusinessFieldId,
                BusinessFieldName = x.BusinessField.Name,
                x.SiteId,
                x.Name,
                x.RepresentativeName,
                x.SalesName,
                x.PhoneNo,
                x.SalesPhoneNo,
                x.FaxNo,
                x.RegistrationNo,
                x.HomepageUri,
                x.Address1,
                x.Adderss2,
                x.AddressZip1,
                x.AddressZip2,
                x.Note,
                x.IsUse,
            }).FirstOrDefault();
            return Ok(item);
        }


        /// <summary>
        /// 저장
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("[action]")]
        public IActionResult Save([FromBody] CmPartner data) {
            if (ModelState.IsValid) {
                _service.Save(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<CmPartner> query) {
            var list = query.Select(x => new {
                x.PartnerId,
                x.PartnerTypeId,
                PartnerTypeName = x.PartnerType.Name,
                x.SiteId,
                x.Name,
                x.RepresentativeName,
                x.PhoneNo,
                x.SalesPhoneNo,
                x.IsUse,
            });
            return list;
        }

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