using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{
    //[Authority]
    public class RoleFController : BaseController
    {
        private BLL.T_Sys_RoleFunction roleFunctionBll = new BLL.T_Sys_RoleFunction();
        private BLL.T_Sys_RoleInfo roleInfoBll = new BLL.T_Sys_RoleInfo();
        private BLL.T_Sys_ModuleInfo moduleInfoBLL = new BLL.T_Sys_ModuleInfo();
        private BLL.T_Sys_ModuleFunctions moduleFunctionsBLL = new BLL.T_Sys_ModuleFunctions();//20180718 此表数据需要清空，不然会影响角色分配（原本是权限按钮表，目前没有做此功能）
        private BLL.T_Sys_RoleFunction roleFunctionBLL = new BLL.T_Sys_RoleFunction();
        //保存角色权限
        public ActionResult SaveRoleFunction(string[] functionIds, int roleId = 0)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            DataTable dt = new DataTable();
            if (Request.IsAuthenticated)
            {
              
                    if (functionIds == null)
                        return Error("参数错误");
                    Model.T_Sys_RoleFunction RoleModel = new Model.T_Sys_RoleFunction();
                    //查询选中页面中的权限
                    var idStr = string.Join(",", functionIds);
                    if (roleId == 0)
                    {
                        //管理员
                        var model = roleInfoBll.GetModel(17);
                        if (model == null)
                            return Error("管理员用户不存在");
                        roleId = model.F_RoleId;
                        new BLL.T_Sys_RoleFunction().Delete1(roleId);
                        var childFuncIdList = moduleFunctionsBLL.DataTableToList(moduleFunctionsBLL.GetList(" F_ParentId in (" + idStr + ") ").Tables[0]).Select(x => x.F_FunctionId).ToList();
                        childFuncIdList.AddRange(functionIds.ToList().Select(x => Convert.ToInt32(x)).ToList());
                        var query = childFuncIdList.Distinct();
                        foreach (var funcId in query)
                        {
                            RoleModel.F_RoleId = roleId;
                            RoleModel.F_FunctionId = funcId;
                            if (!roleFunctionBll.Add(RoleModel))
                                res = Error("权限设置失败");
                            else
                                res = Success("权限设置成功");
                        }
                    }
                    else
                    {
                        new BLL.T_Sys_RoleFunction().Delete1(roleId);
                        var childFuncIdList = moduleFunctionsBLL.DataTableToList(moduleFunctionsBLL.GetList(" F_ParentId in (" + idStr + ") ").Tables[0]).Select(x => x.F_FunctionId).ToList();
                        childFuncIdList.AddRange(functionIds.ToList().Select(x => Convert.ToInt32(x)).ToList());
                        var query = childFuncIdList.Distinct();
                        foreach (var funcId in query)
                        {
                            RoleModel.F_RoleId = roleId;
                            RoleModel.F_FunctionId = funcId;
                            if (!roleFunctionBll.Add(RoleModel))
                                res = Error("权限设置失败");
                            else
                                res = Success("权限设置成功");
                        }
                    }
           
                    dt.Clear();
                    dt.Dispose();
                
            }
            return res;
        }

        /// <summary>
        /// 获取用户权限树形结构
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public ActionResult GetRoleFunction(int roleId = 0)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                
                var moduleInfoList = moduleInfoBLL.DataTableToList(moduleInfoBLL.GetList(" F_StateFlag=1 order by F_Sort").Tables[0]);
                if (roleId == 0) { roleId = 17; }
                var list = roleFunctionBLL.GetModelList(" F_RoleId=" + roleId).Select(x => x.F_FunctionId).ToList();
                res = Success("加载成功", moduleInfoList.Select(x => new
                {
                    id = x.F_ModuleId,
                    pid = x.F_ParentID,
                    name = x.F_ModuleName,
                    ischecked = list.Where(y => y == x.F_ModuleId).Count() > 0 ? true : false
                }));
            }
            return res;
        }
        /// <summary>
        /// 转换树形结构
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        //public List<Model.TreeModel> BindTree(DataTable tab, string parentid)
        //{
        //    DataTable tab2 = new DataTable();

        //    if (tab != null && tab.Rows.Count > 0)
        //    {
        //        List<Model.T_Sys_ModuleFunctions> categorylist = new BLL.T_Sys_ModuleFunctions().DataTableToList(tab);
        //        List<Model.TreeModel> modelList = new List<Model.TreeModel>(categorylist.Count);
        //        for (int i = 0; i < categorylist.Count; i++)
        //        {
        //            Model.TreeModel model = new Model.TreeModel();
        //            string currentID = categorylist[i].F_FunctionId.ToString();//当前功能ID
        //            model.id = currentID;
        //            model.IconCls = "1";//图标
        //            model.text = categorylist[i].F_Name;
        //            tab2 = new BLL.T_Sys_ModuleFunctions().GetList("F_ParentId=" + currentID + " and F_StateFlag=1 and  F_Type<2 order by F_Sort").Tables[0];
        //            if (tab2 != null && tab2.Rows.Count > 0)
        //            {
        //                model.children = BindTree(tab2, "0");
        //            }
        //            modelList.Add(model);
        //        }
        //        return modelList;
        //    }
        //    else
        //    {
        //        return null;
        //    }
        //}

    }
}
