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

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace ConfigurationApi.Controllers
{
    /// <summary>
    /// 角色的菜单按钮信息控制器
    /// </summary>
    [Authorize]
    [Route("api/[controller]")]
    public class RoleFunctionController : BaseController
    {

        private readonly ILogger<RoleFunctionController> _logger;
        private readonly ISys_Role_InfoRepository _sys_role_infoRepository;
        private readonly ISys_Role_FunctionRepository _sys_role_functionRepository;
        private readonly ISys_Module_InfoRepository _sys_module_infoRepository;
        private readonly ISys_ModuleButton_InfoRepository _sys_modulebutton_infoRepository;

        public RoleFunctionController(ISys_Role_InfoRepository sys_role_infoRepository, ISys_Role_FunctionRepository sys_role_functionRepository, ISys_Module_InfoRepository sys_module_infoRepository, ISys_ModuleButton_InfoRepository sys_modulebutton_infoRepository, ILogger<RoleFunctionController> logger)
        {
            _sys_role_functionRepository = sys_role_functionRepository;
            _sys_role_infoRepository = sys_role_infoRepository;
            _sys_module_infoRepository = sys_module_infoRepository;
            _sys_modulebutton_infoRepository= sys_modulebutton_infoRepository;
            _logger = logger;
        }

        /// <summary>
        /// 保存当前选中的权限
        /// </summary>
        /// <param name="functionIds"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [HttpPost("saverolefunction")]
        public async Task<IActionResult> SaveRoleFunctionAsync(string[] ids, string role_id)
        {
            if (ids == null)
                return Error("参数错误");
            var list_model = new List<Sys_Role_Function>();
            await _sys_role_functionRepository.Remove(x=>x.role_id==role_id);
            foreach (var funcId in ids)
            {
                // Moudle_11 Button_13
                string[] _array = funcId.Split('_');
                var _enum = (EnumRoleControlType)Enum.Parse(typeof(EnumRoleControlType), _array[0]);
                var model = new Sys_Role_Function();
                model.role_id = role_id;
                model.function_id= _array[1];
                model.function_type = (int)_enum;
                model.role_type = 1;
                list_model.Add(model);
           
            }

            if (await _sys_role_functionRepository.AddRange(list_model))
            {
                return Success("权限设置成功!");
            }
            else
            {
                return Error("权限设置失败!");
            }
       
        }

        /// <summary>
        /// 获取用户权限树形结构
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [HttpGet("getrolefunction")]
        public async Task<IActionResult> GetRoleFunctionAsync(string role_id)
        {
            var moduleInfoList = (await _sys_module_infoRepository.Get(x=>x.state_flag==1)).OrderBy(x => x.sort).ThenBy(x=>x.parent_id).ThenByDescending(x=>x.lastmodify_time).ToList();
            
            var moduleInfoButtonList = (await _sys_modulebutton_infoRepository.Get(x => x.state_flag == 1)).OrderBy(x => x.sort).ToList(); 

            var roleFunctionlist = (await _sys_role_functionRepository.Get(x => x.role_id == role_id)).Select(x => new { x.function_id, x.function_type });


            var treeList = new List<Models.Dto.RoleFDto>();

            foreach (var item in moduleInfoList.ToArray())
            {
                //判断父菜单是否使用 （循环所有父父，祖宗之上均能判断）
                if (item.parent_id != "000000000000000000000000")
                {
                    if (moduleInfoList.Count(t => t.id == item.parent_id) == 0)
                    {
                        moduleInfoList.Remove(item);
                        continue;
                    }
                }



                Models.Dto.RoleFDto tree = new Models.Dto.RoleFDto();
                tree.id = EnumRoleControlType.Moudle.ToString() + "_" + item.id.ToString();
                tree.pid = EnumRoleControlType.Moudle.ToString() + "_" + item.parent_id.ToString();
                tree.name = item.module_name;
                tree.ischecked = roleFunctionlist.Count(t => (t.function_id == item.id && t.function_type == (int)EnumRoleControlType.Moudle)) == 0 ? false : true;
                tree.type = EnumRoleControlType.Moudle.ToString();
                treeList.Add(tree);
            }


            foreach (var item in moduleInfoButtonList)
            {
                //如果在菜单中找不到按钮归属的菜单id,那么证明此菜单禁用或者被删除，所以不需要显示按钮
                if (moduleInfoList.Count(t => t.id == item.moudle_id) == 0) continue;

                Models.Dto.RoleFDto tree = new Models.Dto.RoleFDto();
                tree.id = EnumRoleControlType.Button.ToString() + "_" + item.id.ToString();
                tree.pid = EnumRoleControlType.Moudle.ToString() + "_" + item.moudle_id.ToString();
                tree.name = item.full_name;
                tree.ischecked = roleFunctionlist.Count(t => (t.function_id == item.id && t.function_type == (int)EnumRoleControlType.Button)) == 0 ? false : true;
                tree.type = EnumRoleControlType.Button.ToString();
                treeList.Add(tree);
            }

            return Success("权限树形加载成功", treeList);
        }



    }
}
