using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.Linq;
using System.Model;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace TVShoppingCallCenter_ZLJ.Controllers.System
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class MenuController : BaseController
    {
        private readonly ISys_RoleFunctionRepository _sys_role_functionRepository;
        private readonly ISys_ModuleInfoRepository _sys_module_infoRepository;
        private readonly ISys_ModuleButtonInfoRepository _sys_modulebutton_infoRepository;

        public MenuController(ISys_ModuleInfoRepository sys_moduleInfoRepository, ISys_RoleFunctionRepository sys_role_functionRepository, ISys_ModuleButtonInfoRepository sys_modulebuttonInfoRepository
            )
        {
            _sys_module_infoRepository = sys_moduleInfoRepository;
            _sys_role_functionRepository = sys_role_functionRepository;
            _sys_modulebutton_infoRepository = sys_modulebuttonInfoRepository;
        }
        /// <summary>
        /// 获取菜单及按钮
        /// </summary>
        /// <returns></returns>
        [HttpGet("getmenutree")]
        public async Task<IActionResult> GetMenuTreeAsync()
        {
            var roleId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role).Value;
            var data = await _sys_role_functionRepository.GetMenuAsync(int.Parse(roleId));
            return Success("成功", data);
        }

        /// <summary>
        /// 获取菜单及按钮
        /// </summary>
        /// <returns></returns>
        [HttpGet("getcurrentmsg")]
        public async Task<IActionResult> GetCurrentMsgAsync()
        {
            var data = new
            {
                authorizeMenu = await GetMenuAsync(),
                authorizeButton = await GetMenuButtonAsync()
            };
            return Content(data.ToJson());
        }

        #region 私有方法
        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        private async Task<object> GetMenuAsync()
        {
            var roleId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role).Value;

            var role_function_list = (await _sys_role_functionRepository.GetListALL(x => x.F_RoleId == int.Parse(roleId) && x.F_FunctionType == (int)EnumRoleControlType.Moudle)).Select(x=>x.F_FunctionId).ToList();

            var authModuleFunctionList = (await _sys_module_infoRepository.GetListALL(x => x.F_State == (int)EnumDelState.Enabled && role_function_list.Contains(x.F_Id))).OrderBy(x => x.F_Sort).OrderByDescending(x => x.F_LastModifyOn).ToList();
            return TreeRecursion(authModuleFunctionList);
        }

        /// <summary>
        /// 获取按钮
        /// </summary>
        /// <returns></returns>
        private async Task<object> GetMenuButtonAsync()
        {
            var roleId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role).Value;

            var functionModuleList = (await _sys_role_functionRepository.GetListALL(x => x.F_RoleId == int.Parse(roleId) && x.F_FunctionType == (int)EnumRoleControlType.Moudle)).Select(x => x.F_FunctionId).ToList();

            var functionButtonList = (await _sys_role_functionRepository.GetListALL(x => x.F_RoleId == int.Parse(roleId) && x.F_FunctionType == (int)EnumRoleControlType.Button)).Select(x => x.F_FunctionId).ToList();

            var authbuttonFunctionList = (await _sys_modulebutton_infoRepository.GetListALL(x => x.F_State == (int)EnumDelState.Enabled && functionButtonList.Contains(x.F_Id))).OrderBy(x => x.F_Sort).ToList();

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

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

        }

        /// <summary>
        /// 生成菜单数据方法
        /// </summary>
        /// <param name="data"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<object> TreeRecursion(List<T_Sys_ModuleInfo> data, int parentId=0)
        {
            List<object> newList = new List<object>();
            List<T_Sys_ModuleInfo> item = data.FindAll(t => t.F_ParentId == parentId);
            if (item.Count > 0)
            {
                foreach (T_Sys_ModuleInfo entity in item)
                {
                    var obj = new
                    {
                        entity.F_Id,
                        entity.F_MenuName,
                        entity.F_MenuCode,
                        entity.F_ParentId,
                        entity.F_OptUrl,
                        entity.F_ImgUrl,
                        entity.F_State,
                        entity.F_Sort,
                        entity.F_IsMenu,
                        entity.F_Target,
                        entity.F_Remark,
                        entity.F_CreateBy,
                        entity.F_CreateOn,
                        entity.F_LastModifyOn,
                        entity.F_LastModifyBy,
                        entity.F_DeleteOn,
                        entity.F_DeleteBy,
                        childnodes = TreeRecursion(data, entity.F_Id)
                    };
                    newList.Add(obj);
                }
            }

            return newList;
        }
        #endregion
    }
}