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 RoleFunctionController : 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_Function functionsBLL = new BLL.T_Sys_Function();
        //保存角色权限
        public ActionResult SaveRoleFunction(string[] functionIds, int roleId = 0)
        {
            DataTable dt = new DataTable();

            if (functionIds == null)
                return Error("参数错误");
            Model.T_Sys_RoleFunction RoleModel = new Model.T_Sys_RoleFunction();
            //查询选中页面中的权限
            var idStr = string.Join(",", functionIds);
            if (roleId != 0)
            {
                var role = roleInfoBll.GetModel(roleId);
                if (role != null)
                {
                    List<string> sqls = new List<string>();
                    string sql = " delete T_Sys_RoleFunction where F_RoleId=" + roleId + ";";
                    sqls.Add(sql);
                    foreach (string fid in functionIds)
                    {
                        var fun = functionsBLL.GetModel(Int32.Parse(fid));
                        if (fun != null)
                        {
                            string sql1 = " insert into T_Sys_RoleFunction(F_RoleId,F_FunctionId) values(" + roleId + "," + fid + ");";
                            sqls.Add(sql1);
                        }
                    }
                    int n = DbHelperSQL.ExecuteSqlTransaction(sqls);

                    return Success("权限设置成功");
                }
                else
                {
                    return Error("参数错误");
                }
            }
            else
            {
                return Error("参数错误");
            }

        }

        /// <summary>
        /// 获取用户权限树形结构
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public ActionResult GetRoleFunction(int roleId = 0)
        {
            var moduleFList = functionsBLL.GetModelList(" F_State=1 ");
            var list = roleFunctionBll.GetModelList(" F_RoleId=" + roleId).Select(x => x.F_FunctionId).ToList();

            return Success("加载成功", moduleFList.Select(x => new
            {
                id = x.F_FunctionId,
                pid = x.F_ParentId,
                name = x.F_FunctionName,
                sort = x.F_Sort,
                ischecked = list.Where(y => y == x.F_FunctionId).Count() > 0 ? true : false
            }).OrderBy(p => p.sort));

        }

    }
}
