using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.Linq;
using System.Model;
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 RoleFunctionController : BaseController
    {
        private readonly ISys_RoleInfoRepository _sys_role_infoRepository;
        private readonly ISys_RoleFunctionRepository _sys_role_functionRepository;
        private readonly ISys_ModuleInfoRepository _sys_module_infoRepository;
        private readonly ISys_ModuleButtonInfoRepository _sys_modulebutton_infoRepository;

        public RoleFunctionController(ISys_RoleInfoRepository sys_role_infoRepository, ISys_RoleFunctionRepository sys_role_functionRepository, ISys_ModuleInfoRepository sys_module_infoRepository, ISys_ModuleButtonInfoRepository sys_modulebutton_infoRepository)
        {
            _sys_role_functionRepository = sys_role_functionRepository;
            _sys_role_infoRepository = sys_role_infoRepository;
            _sys_module_infoRepository = sys_module_infoRepository;
            _sys_modulebutton_infoRepository = sys_modulebutton_infoRepository;
        }

        /// <summary>
        /// 保存当前选中的权限
        /// </summary>
        /// <param name="functionIds"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [HttpPost("saverolefunction")]
        public async Task<IActionResult> SaveRoleFunctionAsync(string[] ids, int role_id)
        {
            if (ids.Length <= 0 || ids == null)
                return Error("请选择菜单或按钮");
            var list_model = new List<T_Sys_RoleFunction>();

            await _sys_role_functionRepository.Delete(x => x.F_RoleId == 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 T_Sys_RoleFunction();
                model.F_RoleId = role_id;
                model.F_FunctionId = int.Parse(_array[1]);
                model.F_FunctionType = (int)_enum;
                list_model.Add(model);

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

        }

        /// <summary>
        /// 获取用户权限树形结构
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [HttpGet("getrolefunction")]
        public async Task<IActionResult> GetRoleFunctionAsync(int role_id)
        {
           
            var moduleInfoList = await _sys_module_infoRepository.GetListALL(x => x.F_State == (int)EnumDelState.Enabled, o => o.F_ParentId, SqlSugar.OrderByType.Asc);
            
            var moduleInfoButtonList = await _sys_modulebutton_infoRepository.GetListALL(x => x.F_State == (int)EnumDelState.Enabled, o => o.F_Sort, SqlSugar.OrderByType.Asc);

            
            var roleFunctionlist = await _sys_role_functionRepository.GetListALL(x => x.F_RoleId == role_id);


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

            foreach (var item in moduleInfoList.ToArray())
            {
                //判断父菜单是否使用 （循环所有父父，祖宗之上均能判断）
                if (item.F_ParentId != 0)
                {
                    if (moduleInfoList.Count(t => t.F_Id == item.F_ParentId) == 0)
                    {
                        moduleInfoList.Remove(item);
                        continue;
                    }
                }
                var count= roleFunctionlist.Count(t => t.F_FunctionId == item.F_Id && t.F_FunctionType == (int)EnumRoleControlType.Moudle);


                Models.Dtos.RoleFDto tree = new Models.Dtos.RoleFDto();
                tree.id = EnumRoleControlType.Moudle.ToString() + "_" + item.F_Id.ToString();
                tree.pid = EnumRoleControlType.Moudle.ToString() + "_" + item.F_ParentId.ToString();
                tree.name = item.F_MenuName;
                tree.ischecked = roleFunctionlist.Count(t => (t.F_FunctionId == item.F_Id && t.F_FunctionType == (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.F_Id == item.F_MenuId) == 0) continue;

                Models.Dtos.RoleFDto tree = new Models.Dtos.RoleFDto();
                tree.id = EnumRoleControlType.Button.ToString() + "_" + item.F_Id.ToString();
                tree.pid = EnumRoleControlType.Moudle.ToString() + "_" + item.F_MenuId.ToString();
                tree.name = item.F_ButtonName;
                tree.ischecked = roleFunctionlist.Count(t => (t.F_FunctionId == item.F_Id && t.F_FunctionType == (int)EnumRoleControlType.Button)) == 0 ? false : true;
                tree.type = EnumRoleControlType.Button.ToString();
                treeList.Add(tree);
            }

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