using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MadRunFabric.Common;
using Microsoft.Extensions.Logging;
using ConfigurationApi.IRepositories;
using MongoDB.Driver;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using MadRunFabric.Model;

namespace ConfigurationApi.Controllers
{
    /// <summary>
    /// 菜单展示
    /// </summary>
   //[Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class MenuController : BaseController
    {
        private readonly ILogger<DictionaryController> _logger;
        private readonly ISys_Module_InfoRepository _sys_moduleInfoRepository;
        private readonly ISys_ModuleButton_InfoRepository _sys_modulebuttonInfoRepository;
        private readonly ISys_Role_FunctionRepository _sys_role_functionRepository;
        public MenuController(
            ILogger<DictionaryController> logger, ISys_Module_InfoRepository sys_moduleInfoRepository, ISys_Role_FunctionRepository sys_role_functionRepository, ISys_ModuleButton_InfoRepository sys_modulebuttonInfoRepository
            )
        {
            _logger = logger;
            _sys_moduleInfoRepository = sys_moduleInfoRepository;
            _sys_role_functionRepository = sys_role_functionRepository;
            _sys_modulebuttonInfoRepository = sys_modulebuttonInfoRepository;
        }

        /// <summary>
        /// 获取菜单及按钮
        /// </summary>
        /// <returns></returns>
        [HttpGet("getmenutree")]
        public IActionResult GetMenuTree()
        {
            var roleId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role).Value;
            var data = _sys_role_functionRepository.GetMenu(roleId);
            return Success("成功", data);
        }

        /// <summary>
        /// 获取菜单及按钮
        /// </summary>
        /// <returns></returns>
        [HttpGet("getcurrentmsg")]
        public IActionResult GetCurrentMsg()
        {

            var MenuAsync = this.GetMenuAsync();
            var MenuButtonAsync = this.GetMenuButtonAsync();
            if (MenuAsync.Result == null || MenuButtonAsync == null)
            {
                return Content("没有权限");
            }
            else
            {
                var data = new
                {
                    authorizeMenu = MenuAsync,
                    authorizeButton = MenuButtonAsync
                };
                return Content(data.ToJson());
            }
           
        }

        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        private async Task<object> GetMenuAsync()
        {
            var roleId =  User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role).Value;//"5aaa5a54b9c1893cb015df26";//
            var role_function_list = (await _sys_role_functionRepository.Get(x =>x.role_id== roleId)).ToList();
            var list = role_function_list.Where(x => (x.function_type == (int)EnumRoleControlType.Moudle)).Select(x => x.function_id);
            var moduleInfoList = (await _sys_moduleInfoRepository.Get(x=>x.state_flag==1)).ToList();
            moduleInfoList = moduleInfoList.OrderBy(x => x.sort).ThenByDescending(x => x.lastmodify_time).ToList();
            var authModuleFunctionList = moduleInfoList.Where(x => list.Contains(x.id)).ToList();
            return TreeRecursion(authModuleFunctionList);
        }

        /// <summary>
        /// 获取按钮
        /// </summary>
        /// <returns></returns>
        private async Task<object> GetMenuButtonAsync()
        {
            var roleId =  User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role).Value;//"5aaa5a54b9c1893cb015df26";// 
            var role_function_list = (await _sys_role_functionRepository.Get(x => x.role_id == roleId)).ToList();
            var functionModuleList = role_function_list.Where(x => (x.function_type == (int)EnumRoleControlType.Moudle)).Select(x => x.function_id);
            var functionButtonList = role_function_list.Where(x => (x.function_type == (int)EnumRoleControlType.Button)).Select(x => x.function_id);
            var moduleInfoButtonList = (await _sys_modulebuttonInfoRepository.Get(x => x.state_flag == 1)).ToList();
            moduleInfoButtonList.Sort((x, y) => x.sort - y.sort);
            var buttonList = moduleInfoButtonList.Where(x => functionButtonList.Contains(x.id)).ToList();

            Dictionary<string, object> dictionary = new Dictionary<string, object>();

            foreach (var item in functionModuleList)
            {
                var _list = buttonList.Where(x => x.moudle_id == item).ToList();
                dictionary.Add(item.ToString(), _list);
            }
            return dictionary;


        }

        /// <summary>
        /// 生成菜单数据方法
        /// </summary>
        /// <param name="data"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<Sys_Module_Info> TreeRecursion(List<Sys_Module_Info> data, string parentId = "000000000000000000000000")
        {
            List<Sys_Module_Info> newList = new List<Sys_Module_Info>();
            List<Sys_Module_Info> item = data.FindAll(t => t.parent_id == parentId);//data建议在调用此扩展方法前已经排序过
            if (item.Count > 0)
            {
                foreach (Sys_Module_Info entity in item)
                {
                    entity.childnodes = TreeRecursion(data, entity.id.ToString());
                    newList.Add(entity);
                }
            }

            return newList;
        }

    }
}