using CrazyStudio.Core.Common.Eitities.Page;
using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;
using XPrintServer.Business.Dto;
using XPrintServer.Business.Services;
using XPrintServer.DataModel.Models;

namespace XPrintServer.Admin.Api.Controllers
{

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MenuController : ControllerBase
    {

        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly MenuService _menuService;
        private readonly UserMenuInRoleService _userMenuInRoleService;
        private readonly ActionLogService _actionLogService;

        public MenuController(IHttpContextAccessor httpContextAccessor, MenuService menuService, UserMenuInRoleService userMenuInRoleService, ActionLogService actionLogService)
        {
            _httpContextAccessor = httpContextAccessor;
            _menuService = menuService;
            _userMenuInRoleService = userMenuInRoleService;
            _actionLogService = actionLogService;
        }

        [HttpPost]
        public async Task<ActionResult> AddOrUpdateMenu([FromBody] Menu menu)
        {
            try
            {
                await _menuService.AddOrUpdateMenu(menu);
                return Ok(menu);
            }
            catch (Exception ex)
            {
                await _actionLogService.AddActionLog(new ActionLog { Title = "AddOrUpdateMenu Error", Content = ex.Message + " " + ex.StackTrace, DateTime = DateTime.Now });
                return StatusCode(500, ex.Message);
            }
        }


        [HttpPost]
        public async Task<ActionResult> MenuList([FromBody] PageData pageData)
        {
            try
            {
                var menuList = await _menuService.GetMenuList(pageData, false);
                return Ok(menuList);
            }
            catch (Exception ex)
            {
                await _actionLogService.AddActionLog(new ActionLog { Title = "MenuList Error", Content = ex.Message + " " + ex.StackTrace, DateTime = DateTime.Now });
                return StatusCode(500, ex.Message);
            }
        }

        [HttpPost]
        public async Task<ActionResult<List<MenuTreeData>>> AllMenuList()
        {
            try
            {
                var menuList = await _menuService.GetListAsync().ConfigureAwait(false);
                List<MenuTreeData> menuTreelist = menuList.ConvertAll(m => new MenuTreeData
                {
                    Id = m.Id,
                    ComponentPath = m.ComponentPath,
                    MenuName = m.MenuName,
                    RouteName = m.RouteName,
                    ParentId = m.ParentId,
                    IsActive = m.IsActive
                })!;
                List<MenuTreeData> removeList = new List<MenuTreeData>();
                foreach (var menu in menuTreelist)
                {
                    var parentMenu = menuTreelist.Find(m => m.Id == menu.ParentId);
                    if (parentMenu != null)
                    {
                        parentMenu.Children.Add(menu);
                        removeList.Add(menu);
                    }
                }
                foreach (var removeMenu in removeList)
                {
                    menuTreelist.Remove(removeMenu);
                }

                return Ok(menuTreelist);
            }
            catch (Exception ex)
            {
                await _actionLogService.AddActionLog(new ActionLog { Title = "AllMenuList Error", Content = ex.Message + " " + ex.StackTrace, DateTime = DateTime.Now });
                return StatusCode(500, ex.Message);
            }
        }

        [HttpPost]
        public async Task<ActionResult> ActiveMenuList([FromBody] PageData pageData)
        {
            try
            {
                var menuList = await _menuService.GetMenuList(pageData, true);
                return Ok(menuList);
            }
            catch (Exception ex)
            {
                await _actionLogService.AddActionLog(new ActionLog { Title = "ActiveMenuList Error", Content = ex.Message + " " + ex.StackTrace, DateTime = DateTime.Now });
                return StatusCode(500, ex.Message);
            }
        }


        [HttpPost]
        public async Task<ActionResult> MenuById([FromBody] Guid Id)
        {
            try
            {
                var menu = await _menuService.GetByIdAsync(Id).ConfigureAwait(false);
                return Ok(menu);
            }
            catch (Exception ex)
            {
                await _actionLogService.AddActionLog(new ActionLog { Title = "MenuById Error", Content = ex.Message + " " + ex.StackTrace, DateTime = DateTime.Now });
                return StatusCode(500, ex.Message);
            }
        }


        [HttpPost]
        public async Task<ActionResult> DeleteMenu([FromBody] Guid Id)
        {
            try
            {
                //开始事务
                await _menuService.Context.Ado.BeginTranAsync();
                var isOK = await _menuService.DeleteByIdAsync(Id);

                var deleteDatas = await _userMenuInRoleService.Context.Queryable<UserMenuInRole>().Where(um => um.MenuId == Id).SplitTable().ToListAsync().ConfigureAwait(false);
                await _userMenuInRoleService.Context.Deleteable(deleteDatas).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);

                //提交事务
                await _menuService.Context.Ado.CommitTranAsync();
                return Ok(isOK);
            }
            catch (Exception ex)
            {
                //异常事务回滚
                await _menuService.Context.Ado.RollbackTranAsync();
                await _actionLogService.AddActionLog(new ActionLog { Title = "DeleteMenu Error", Content = ex.Message + " " + ex.StackTrace, DateTime = DateTime.Now });
                return StatusCode(500, ex.Message);
            }
        }
    }
}
