using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers.System
{
    public class RoleController : BaseController
    {
        private Bll.T_Sys_Role roleBLL = new Bll.T_Sys_Role();

        // GET: Role

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList(string rolecode,string rolename, int pageindex = 1, int pagesize = 10)
        {
            DataTable dt = new DataTable();
            string sql = string.Empty;         
            if (!string.IsNullOrWhiteSpace(rolecode))
            {
                sql += " and F_RoleCode like '%" + rolecode + "%'";
            }
            if (!string.IsNullOrWhiteSpace(rolename))
            {
                sql += " and F_RoleName like '%" + rolename + "%'";
            }
            int recordCount = 0;
            dt = Bll.PagerBll.GetListPager(
                                    "T_Sys_Role with(nolock)",
                                    "F_RoleId",
                                    "*,dbo.GetUserNameNew(F_CreateUser) F_CreateName ",
                                    sql,
                                    "ORDER BY F_Sort",
                                    pagesize,
                                    pageindex,
                                    true,
                                    out recordCount);
            var obj = new
            {
                state = "success",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="roleid"></param>
        /// <param name="rolecode"></param>
        /// <returns></returns>
        public ActionResult GetModel(int roleid = 0, string rolecode = "")
        {
            string sql = " 1=1 ";
            if (roleid > 0)
            {
                sql += " and F_RoleId=" + roleid;
            }
            if (!string.IsNullOrWhiteSpace(rolecode))
            {
                sql += " and F_RoleCode='" + rolecode + "'";
            }
            if (string.IsNullOrWhiteSpace(sql))
                return Error("获取失败");

            var role = roleBLL.GetModelList(sql).FirstOrDefault();

            return Success("获取成功", role);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Add(string code, string name, int? sort=0)
        {
            if (roleBLL.Exists(code))
            {
                return Error("已经存在此编码");
            }
            else
            {
                Model.T_Sys_Role dModel = new Model.T_Sys_Role();
                dModel.F_Sort = sort;
                dModel.F_RoleCode = code;
                dModel.F_RoleName = name;
                dModel.F_State = 1;
                dModel.F_CreateTime = DateTime.Now;
                dModel.F_CreateUser = User.F_UserCode;

                int n = roleBLL.Add(dModel);
                if (n > 0)
                {
                    return Success("添加成功", n);
                }

                else
                    return Error("添加失败");
            }

        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult  Edit(int id, string code, string name, int sort)
        {
            Model.T_Sys_Role dModel = roleBLL.GetModel(id);
            if (dModel != null)
            {
                var list = roleBLL.GetModelList(" F_RoleCode='" + code + "' and F_RoleId!='" + id + "' ");
                if (list.Count > 0)
                {
                    return Error("已经存在此编码");
                }
                else
                {
                    dModel.F_Sort = sort;
                    dModel.F_RoleCode = code;
                    dModel.F_RoleName = name;
                    dModel.F_Sort = sort;
                    dModel.F_State = 1;

                    if (roleBLL.Update(dModel))
                    {
                        return Success("修改成功");
                    }
                    else
                        return Error("修改失败");
                }
            }
            else
            {
                return Error("修改失败");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(string[] ids)
        {
            if (ids != null && ids.Count() > 0)
            {
                bool bl = true;
                var idStr = string.Join(",", ids);
                var list1 = new Bll.T_Sys_UserAccount().GetList("F_RoleId in (" + idStr + ")").Tables[0];
                if (list1.Rows.Count == 0)
                {
                    bl = false;
                }
                if (bl)
                {
                    return Error("正在被使用，不能删除");
                }

                if (roleBLL.DeleteList(idStr))
                {
                    return Success("删除成功");
                }
                else
                {
                    return Error("删除失败");
                }
            }
            else
            {
                return Error("删除失败");
            }
        }

        /// <summary>
        /// 获取权限
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public ActionResult GetRoleFunction(int roleid=0)
        {
            //var moduleFList = new Bll.T_Sys_Menu().GetModelList(" F_State=1 and (F_Type=1 or F_Type=2) ");
            var moduleFList = new Bll.T_Sys_Menu().GetModelList(" F_State=1 ");
            var list=new DataTable();
            if (roleid > 0)
            {

                list = DB.DbHelperSQL.Query("select F_MenuId from T_Sys_RoleMenu with(nolock) where F_RoleId=" + roleid).Tables[0];
            }

            if(list.Rows.Count>0)
            return Success("加载成功", moduleFList.Select(x => new
            {
                id = x.F_MenuId,
                pid = x.F_ParentId,
                name = x.F_MenuName,
                sort = x.F_Sort,
                ischecked = list.Select("F_MenuId=" + x.F_MenuId).Count() > 0 ? true : false
            }).OrderBy(p => p.sort));
            else return Success("加载成功", moduleFList.Select(x => new
            {
                id = x.F_MenuId,
                pid = x.F_ParentId,
                name = x.F_MenuName,
                sort = x.F_Sort,
                ischecked = false
            }).OrderBy(p => p.sort));
        }

        /// <summary>
        /// 保存权限
        /// </summary>
        /// <param name="roleid">角色id</param>
        /// <param name="menuids">菜单id集合</param>
        /// <returns></returns>
        public ActionResult SaveRoleFunction(int roleid, string[] menuids)
        {
            DataTable dt = new DataTable();

            if (menuids == null || roleid == 0)
                return Error("参数错误");

            var idStr = string.Join(",", menuids);

            var role = roleBLL.GetModel(roleid);
            if (role != null)
            {
                List<string> sqls = new List<string>();
                string sql = " delete T_Sys_RoleMenu where F_RoleId=" + roleid + ";";
                sqls.Add(sql);
                foreach (string mid in menuids)
                {
                    string sql1 = " insert into T_Sys_RoleMenu(F_RoleId,F_MenuId) values(" + roleid + "," + mid + ");";
                    sqls.Add(sql1);
                }
                int n = DB.DbHelperSQL.ExecuteSqlTransaction(sqls);
                if (n > 0)
                {
                    CacheHelper.Remove("RoleMenus_" + roleid);
                    CacheHelper.Remove("RoleActions_" + roleid);
                    CacheHelper.Remove("RoleButtons_" + roleid);
                    
                    return Success("保存成功");
                }
                else
                {
                    return Error("保存失败");
                }
            }
            else
            {
                return Error("参数错误");
            }
        }
    }
}