using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;

namespace FineUIPro.Web.common.SysManage
{
    public partial class RolePower : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string lan = string.Empty;
                if (this.GetLanguage == "en-US")
                {
                    lan = "en";
                }
                else
                {
                    lan = "zh";
                }
                var module = from x in BLL.DropListService.GetSystemList(lan) where x.Value != Const.System_4 select x;
                drpMenuModule.DataTextField = "Text";
                drpMenuModule.DataValueField = "Value";
                drpMenuModule.DataSource = module;
                drpMenuModule.DataBind();
                Funs.FineUIPleaseSelect(drpMenuModule);

                InitTreeMenu();
                //BindGrid();
            }
        }

        #region BindGrid

        private void BindGrid()
        {
            string strSql = @"SELECT MenuId,MenuName,SuperMenu FROM dbo.Sys_Menu
                              WHERE MenuModule=@MenuModule
                              ORDER BY MenuModule, SortIndex";

            if (this.GetLanguage == "en-US")
            {
                strSql = @"SELECT MenuId,MenuEnName AS MenuName,SuperMenu FROM dbo.Sys_Menu
                              WHERE MenuModule=@MenuModule
                              ORDER BY MenuModule, SortIndex";
            }
                List<SqlParameter> parms = new List<SqlParameter>();
            parms.Add(new SqlParameter("@MenuModule", this.drpMenuModule.SelectedValue));
            SqlParameter[] parameter = parms.ToArray();

            DataTable dt = SQLHelper.GetDataTableRunText(strSql, parameter);
           
            Grid1.DataSource = dt;
            Grid1.DataBind();

        }
        #endregion


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            if (tvRole.SelectedNode == null || tvRole.SelectedNodeID == "0")
            {
                Alert.ShowInTop("请选择角色!", MessageBoxIcon.Warning);
                return;
            }
            if (drpMenuModule.SelectedValue == Const._Null)
            {
                Alert.ShowInTop("请选择授权模块!", MessageBoxIcon.Warning);
                return;
            }
            this.BindGrid();
        }


        #region 增加按钮事件
        /// <summary>
        /// 增加按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.RolePowerMenuId, Const.BtnSave))
            {
                if (tvRole.SelectedNode == null || tvRole.SelectedNodeID == "0")
                {
                    Alert.ShowInTop("请选择角色!", MessageBoxIcon.Warning);
                    return;
                }
                if (drpMenuModule.SelectedValue == Const._Null)
                {
                    Alert.ShowInTop("请选择授权模块!", MessageBoxIcon.Warning);
                    return;
                }

                Model.HJGLDB db = Funs.DB;
                var power = from x in db.Sys_RolePower
                            join y in db.Sys_Menu on x.MenuId equals y.MenuId
                            where  x.RoleId == tvRole.SelectedNodeID && y.MenuModule == drpMenuModule.SelectedValue
                            select x;
                db.Sys_RolePower.DeleteAllOnSubmit(power);
                db.SubmitChanges();

                for (int i = 0; i < this.Grid1.Rows.Count; i++)
                {
                    string buttonToMenuIds = string.Empty;
                    System.Web.UI.WebControls.CheckBoxList cblButtonPower = (System.Web.UI.WebControls.CheckBoxList)(this.Grid1.Rows[i].FindControl("cblButtonPower"));
                    if (cblButtonPower.SelectedItem != null)
                    {
                        foreach (System.Web.UI.WebControls.ListItem item in cblButtonPower.Items)
                        {
                            if (item.Selected)
                            {
                                buttonToMenuIds += item.Value + ",";
                            }
                        }
                        if (!string.IsNullOrEmpty(buttonToMenuIds))
                        {
                            buttonToMenuIds = buttonToMenuIds.Substring(0, buttonToMenuIds.LastIndexOf(","));
                        }

                        string newKeyID = SQLHelper.GetNewID(typeof(Model.Sys_RolePower));
                        Model.Sys_RolePower newPower = new Model.Sys_RolePower();
                        newPower.RolePowerId = newKeyID;
                        newPower.RoleId = tvRole.SelectedNodeID;
                        newPower.MenuId = Grid1.DataKeys[i][0].ToString();
                        newPower.ButtonToMenus = buttonToMenuIds;
                        //newPower.ProjectId = this.CurrUser.LoginProjectId;
                        
                        db.Sys_RolePower.InsertOnSubmit(newPower);
                        db.SubmitChanges();

                        string supMenuId = Grid1.DataKeys[i][1].ToString();
                        InsertSuperMenu(supMenuId, tvRole.SelectedNodeID);
                    }
                }
                ShowNotify("角色权限设置成功!");
                BLL.Sys_LogService.AddLog(Const.System_1, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.RolePowerMenuId, Const.BtnSave, "");
            }
            else
            {
                Alert.ShowInTop(Resources.Lan.NoPrivilegePrompt, MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion

        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            System.Web.UI.WebControls.CheckBoxList cblButtonPower = (System.Web.UI.WebControls.CheckBoxList)(this.Grid1.Rows[e.RowIndex].FindControl("cblButtonPower"));
            string menuId = e.Row.RowID;
            var menu = from x in Funs.DB.Sys_Menu where x.MenuId == menuId select x;
            if (menu != null && menu.Count() > 0)
            {
                var b = from x in Funs.DB.Sys_ButtonToMenu where x.MenuId == menu.First().MenuId orderby x.SortIndex select x;
                if (b != null && b.Count() > 0)
                {
                    cblButtonPower.DataTextField = "ButtonName";
                    if (this.GetLanguage == "en-US")
                    {
                        cblButtonPower.DataTextField = "ButtonEnName";
                    }
                    cblButtonPower.DataValueField = "ButtonToMenuId";
                    cblButtonPower.DataSource = b.ToList();
                    cblButtonPower.DataBind();
                }
                if (tvRole.SelectedNode != null && tvRole.SelectedNodeID != "0")
                {
                    var power = from x in Funs.DB.Sys_RolePower where x.MenuId == menu.First().MenuId 
                                && x.RoleId == tvRole.SelectedNodeID select x;
                    if (power != null && power.Count() > 0)
                    {
                        for (int i = 0; i < cblButtonPower.Items.Count; i++)
                        {
                            if (power.First().ButtonToMenus.Contains(cblButtonPower.Items[i].Value))
                            {
                                cblButtonPower.Items[i].Selected = true;
                            }
                        }
                    }
                }
            }
        }

        protected void tvRole_NodeCommand(object sender, EventArgs e)
        {
            this.InitTreeMenu();
        }

        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            this.BindGrid();
        }

        private void InitTreeMenu()
        {
            this.tvRole.Nodes.Clear();

            TreeNode rootRole = new TreeNode();
            rootRole.Text = "角色";
            if (this.GetLanguage == "en-US")
            {
                rootRole.Text = "Roles";
            }
            rootRole.NodeID = "0";
            rootRole.Expanded = true;
            this.tvRole.Nodes.Add(rootRole);
            BoundTree(rootRole.Nodes);

        }


        /// <summary>
        /// 添加项目
        /// </summary>
        /// <param name="nodes"></param>
        /// <param name="parentId"></param>
        /// <param name="type"></param>
        private void BoundTree(TreeNodeCollection nodes)
        {
            List<Model.Sys_Role> roles = BLL.Sys_RoleService.GetRoleList();
            if (!string.IsNullOrEmpty(this.txtRoleName.Text))
            {
                roles = roles.Where(e => e.RoleName.Contains(this.txtRoleName.Text.Trim())).ToList();
            }
            if (roles.Count() > 0)
            {
                TreeNode tn = null;
                foreach (var q in roles)
                {
                    tn = new TreeNode();
                    tn.Text = q.RoleName;
                    tn.NodeID = q.RoleId;
                    tn.ToolTip = q.Remark;
                    tn.EnableClickEvent = true;
                    nodes.Add(tn);
                }
            }
        }

        private void InsertSuperMenu(string supMenuId,string roleId)
        {
            Model.HJGLDB db = Funs.DB;
            var menuPower = from x in db.Sys_RolePower where x.RoleId==roleId && x.MenuId == supMenuId select x;
            if (menuPower.Count() == 0 && supMenuId != "0")
            {
                string newKeyID = SQLHelper.GetNewID(typeof(Model.Sys_RolePower));
                Model.Sys_RolePower newPower = new Model.Sys_RolePower();
                newPower.RolePowerId = newKeyID;
                newPower.RoleId = roleId;
                newPower.MenuId = supMenuId;
                //newPower.ProjectId = this.CurrUser.LoginProjectId;

                db.Sys_RolePower.InsertOnSubmit(newPower);
                db.SubmitChanges();

                var menu = from x in db.Sys_Menu where x.MenuId == supMenuId select x;
                if (menu.Count() > 0)
                {
                    InsertSuperMenu(menu.First().SuperMenu, roleId);
                }
            }
        }

    }
}