
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using FMSAdmin.Data;
using FMSAdmin.Helpers;
using FMSAdmin.Entities;
using FMSAdmin.Services;
using Microsoft.AspNetCore.Authorization;
using FMSAdmin.Models;

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

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

        /// <summary>
        /// 등록
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult Create([FromBody] Sitemap data) {
            //_logger.LogInformation(data.Dump());

            if (ModelState.IsValid) {
                _service.Save(data);
            } else {
                return BadRequest(ModelState);
            }
            return Ok(new {
                data.SitemapId,
                data.ParentId,
                data.Name,
                data.Path,
                data.Icon,
                data.Action1,
                data.Action2,
                data.Depth,
                data.Position,
            });
        }

        /// <summary>
        /// 수정
        /// </summary>
        /// <param name="id"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("{id}")]
        public IActionResult Edit(int id, [FromBody] Sitemap data) {
            //_logger.LogInformation(data.Dump());

            if (ModelState.IsValid) {
                _service.Save(data);
            } else {
                return BadRequest(ModelState);
            }

            return Ok();
        }

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

            return Ok();
        }

        /// <summary>
        /// 리스트
        /// </summary>
        /// <param name="req"></param>
        /// <param name="siteId"></param>
        /// <returns></returns>
        [HttpGet("search")]
        public IActionResult Search(int siteId, int userGroupId, string keyword, SitemapType type) {
            var query = _service.GetAll();
            query = query.Where(x => x.Type == type);
            query = query.Where(x => x.Hidden == false);

            query = query.Where(x => x.Name.Replace(" ", "").Contains(keyword.Replace(" ", "")));
            query = query.Where(x => x.Path != "");
            query = query.Where(x => x.Depth > 0);
            query = query.OrderBy(x => x.Depth).ThenBy(x => x.Position);

            var list = query.Select(x => new {
                x.SitemapId,
                x.Name,
                ParentName1 = x.Parent.Parent.Parent.Name,
                ParentName2 = x.Parent.Parent.Name,
                ParentName3 = x.Parent.Name,
                x.Path,
                x.Depth,
                x.Memo,
                Auth = x.SitemapAuths.Where(x => x.SiteId == siteId && x.UserGroupId == userGroupId).Select(x => new {
                    x.Access,
                    x.Update,
                    x.Delete,
                    x.Business,
                    x.Action1,
                    x.Action2,
                    x.Action3,
                    x.Action4,
                    x.Action5
                }).FirstOrDefault(),
            });

            return Ok(list.ToList().Where(x => x.Auth == null || (x.Auth != null && x.Auth.Access == true)));
        }


        /// <summary>
        /// 조회
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public IActionResult Get(int id) {
            var data = _service.Gets(id);
            if (data.Count() == 0) {
                return NotFound("자재정보를 찾을 수 없습니다.");
            }
            var item = data.Select(x => new {
                x.SitemapId,
                x.Name,
                x.Path,
                x.Icon,
                x.Action1,
                x.Action2,
                x.Action3,
                x.Action4,
                x.Action5,
                x.Memo,
                x.ParentId,
                x.Position,
                x.Depth
            });

            return Ok(item.First());
        }

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

            // 최대 4뎁스
            var list = query.OrderBy(x => x.Position).Select(c => new {
                key = c.SitemapId,
                title = c.Name,
                children = c.Childs.OrderBy(x => x.Position).Select(c1 => new {
                    key = c1.SitemapId,
                    title = c1.Name,
                    children = c1.Childs.OrderBy(x => x.Position).Select(c2 => new {
                        key = c2.SitemapId,
                        title = c2.Name,
                        children = c2.Childs.OrderBy(x => x.Position).Select(c3 => new {
                            key = c3.SitemapId,
                            title = c3.Name,
                        })
                    })
                })
            });

            return Ok(list);
        }

        /// <summary>
        /// 전체메뉴
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpGet("menu/{type}")]
        public IActionResult Menu(int siteId, int userGroupId, SitemapType type) {
            var query = _service.GetAll().Where(x => x.Type == type && x.ParentId == null);

            // 최대 4뎁스
            var list = query.Where(x => x.Hidden == false).OrderBy(x => x.Position).Select(c => new {
                id = c.SitemapId,
                name = c.Name,
                path = c.Path,
                icon = c.Icon,
                action1 = c.Action1,
                action2 = c.Action2,
                action3 = c.Action3,
                action4 = c.Action4,
                action5 = c.Action5,
                auth = c.SitemapAuths.Where(x => x.SiteId == siteId && x.UserGroupId == userGroupId).Select(x => new {
                    x.Access,
                    x.Update,
                    x.Delete,
                    x.Business,
                    x.Action1,
                    x.Action2,
                    x.Action3,
                    x.Action4,
                    x.Action5
                }).FirstOrDefault(),
                children = c.Childs.Where(x => x.Hidden == false).OrderBy(x => x.Position).Select(c1 => new {
                    id = c1.SitemapId,
                    name = c1.Name,
                    path = c1.Path,
                    icon = c1.Icon,
                    action1 = c1.Action1,
                    action2 = c1.Action2,
                    action3 = c1.Action3,
                    action4 = c1.Action4,
                    action5 = c1.Action5,
                    auth = c1.SitemapAuths.Where(x => x.SiteId == siteId && x.UserGroupId == userGroupId).Select(x => new {
                        x.Access,
                        x.Update,
                        x.Delete,
                        x.Business,
                        x.Action1,
                        x.Action2,
                        x.Action3,
                        x.Action4,
                        x.Action5
                    }).FirstOrDefault(),
                    children = c1.Childs.Where(x => x.Hidden == false).OrderBy(x => x.Position).Select(c2 => new {
                        id = c2.SitemapId,
                        name = c2.Name,
                        path = c2.Path,
                        icon = c2.Icon,
                        action1 = c2.Action1,
                        action2 = c2.Action2,
                        action3 = c2.Action3,
                        action4 = c2.Action4,
                        action5 = c2.Action5,
                        auth = c2.SitemapAuths.Where(x => x.SiteId == siteId && x.UserGroupId == userGroupId).Select(x => new {
                            x.Access,
                            x.Update,
                            x.Delete,
                            x.Business,
                            x.Action1,
                            x.Action2,
                            x.Action3,
                            x.Action4,
                            x.Action5
                        }).FirstOrDefault(),
                        children = c2.Childs.Where(x => x.Hidden == false).OrderBy(x => x.Position).Select(c3 => new {
                            id = c3.SitemapId,
                            name = c3.Name,
                            path = c3.Path,
                            icon = c3.Icon,
                            action1 = c3.Action1,
                            action2 = c3.Action2,
                            action3 = c3.Action3,
                            action4 = c3.Action4,
                            action5 = c3.Action5,
                            auth = c3.SitemapAuths.Where(x => x.SiteId == siteId && x.UserGroupId == userGroupId).Select(x => new {
                                x.Access,
                                x.Update,
                                x.Delete,
                                x.Business,
                                x.Action1,
                                x.Action2,
                                x.Action3,
                                x.Action4,
                                x.Action5
                            }).FirstOrDefault(),
                        })
                    })
                })
            });

            return Ok(list);
        }

        [HttpPost("up/{id}")]
        public IActionResult Up(int id) {
            Sitemap data;
            data = _service.Get(id);
            if (data == null) {
                return NotFound("데이터를 찾을 수 없습니다.");
            }
            _service.Up(data);

            return Ok(data.Position);
        }

        [HttpPost("down/{id}")]
        public IActionResult Down(int id) {
            Sitemap data;
            data = _service.Get(id);
            if (data == null) {
                return NotFound("데이터를 찾을 수 없습니다.");
            }
            _service.Down(data);

            return Ok(data.Position);
        }

        /// <summary>
        /// 사이트맵 업로드
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("upload/{type}")]
        public IActionResult Upload(SitemapType type, [FromBody] Sitemap[] list) {
            _logger.LogInformation(list.Dump());

            _service.Upload(type, list);

            return Ok(list);
        }

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

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

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

            return query;
        }
    }
}