using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

/**************************************
 * 模块：模块数据管理
 * 作者：Nick.Yan
 * 日期: 2008-11-13
 * 网址：www.redglove.com.cn
 * ***********************************/

namespace RedGlovePermission.Web.Admin.Modubles.SysConfig
{
    public partial class ModulesPage : System.Web.UI.Page
    {
        RedGlovePermission.BLL.RGP_Modules bll = new RedGlovePermission.BLL.RGP_Modules();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!SessionBox.CheckUserSession())
            {
                Response.Redirect("~/Admin/Login.aspx");
            }
            else
            {
                //初始化模块权限
                UserHandle.InitModule("Mod_Modules");
                if (!IsPostBack)
                {
                    btn_save.Attributes.Add("onclick", "return CheckAdd()");//加入验证
                    btn_update.Attributes.Add("onclick", "return CheckAdd()");//加入验证
                    BindTypeOrder();
                    BindOrder();
                }
            }
        }

        /// <summary>
        /// 将模块类型数据绑定到DataSet
        /// </summary>
        public void BindTypeOrder()
        {
            RedGlovePermission.BLL.RGP_ModuleType mtbll = new RedGlovePermission.BLL.RGP_ModuleType();
            ModuleType.DataSource = mtbll.GetModuleTypeList("");
            ModuleType.DataTextField = "ModuleTypeName";
            ModuleType.DataValueField = "ModuleTypeID";
            ModuleType.DataBind();
        }

        /// <summary>
        /// 将数据绑定到DataSet
        /// </summary>
        public void BindOrder()
        {
            DataSet ds = bll.GetModuleList("ModuleTypeID=" + ModuleType.SelectedValue);

            if (ds.Tables[0].Rows.Count == 0)
            {
                Glist.Visible = false;
            }
            else
            {
                Glist.Visible = true;
                GridViewMsg.InnerText = "共有" + ds.Tables[0].Rows.Count + "条记录";
            }

            ModuleList.DataSource = ds;
            ModuleList.DataBind();
        }

        //添加时初始化权限
        public void BindPermission()
        {
            StringBuilder strState=new StringBuilder();
            StringBuilder strTag = new StringBuilder();
            strState.Append("<table width=\"200\" border=\"0\" cellpadding=\"0\" cellspacing=\"2\">");

            RedGlovePermission.BLL.RGP_AuthorityDir Abll = new RedGlovePermission.BLL.RGP_AuthorityDir();
            DataSet ds = Abll.GetAuthorityList("", "order by AuthorityOrder asc");

            AuthorityNum.Text = ds.Tables[0].Rows.Count.ToString();
            for(int i=0;i<ds.Tables[0].Rows.Count;i++)
            {
                strState.Append("<tr><td width=\"80\">" + ds.Tables[0].Rows[i]["AuthorityName"]
                    + "</td><td width=\"100\"><table id=\"Alist" + i.ToString()
                    + "\" border=\"0\"><tr><td><input id=\"Alist" + i.ToString()
                    + "_0\" type=\"radio\" name=\"Alist" + i.ToString() + "\" value=\"1\" />"
                    + "<label for=\"Alist" + i.ToString() + "_0\">允许</label></td><td>"
                    + "<input id=\"Alist" + i.ToString() + "_1\" type=\"radio\" name=\"Alist" + i.ToString() + "\" value=\"0\" checked=\"checked\" />"
                    + "<label for=\"Alist" + i.ToString() + "_1\">拒绝</label></td></tr></table></td>");

                //写入标识
                strTag.Append("<input type=\"hidden\" name=\"Atag" + i.ToString() + "\" id=\"Atag" + i.ToString() + "\" value=\"" + ds.Tables[0].Rows[i]["AuthorityTag"] + "\" />");
            }
            strState.Append("</table>");
            divstate.InnerHtml = strState.ToString() + strTag.ToString();           
        }

        //更新时初始化权限
        public void BindPermissionUpdate(int ModuleID)
        {
            #region 模块数据绑定

            RedGlovePermission.Model.RGP_Modules model = new RedGlovePermission.Model.RGP_Modules();
            model=bll.GetModuleModel(ModuleID);
            M_ID.Text = model.ModuleID.ToString();
            ModuleType.SelectedValue = model.ModuleTypeID.ToString();
            txt_Name.Text = model.ModuleName;
            txt_tag.Text = model.ModuleTag;
            txt_url.Text = model.ModuleURL;
            if (model.ModuleDisabled)
            { txt_state.SelectedIndex = 0; }
            else
            { txt_state.SelectedIndex = 1; }

            txt_order.Text = model.ModuleOrder.ToString();
            txt_Description.Text = model.ModuleDescription;

            if (model.IsMenu)
            { IsMenu.SelectedIndex = 0; }
            else
            { IsMenu.SelectedIndex = 1; }

            #endregion

            #region 权限数据绑定

            StringBuilder strState = new StringBuilder();//状态
            StringBuilder strTag = new StringBuilder();//标识
            StringBuilder strVerify = new StringBuilder();//对比状态
            strVerify.Append("<input type=\"hidden\" name=\"verifystate\" id=\"verifystate\" value=\"");
            strState.Append("<table width=\"200\" border=\"0\" cellpadding=\"0\" cellspacing=\"2\">");

            RedGlovePermission.BLL.RGP_AuthorityDir Abll = new RedGlovePermission.BLL.RGP_AuthorityDir();
            RedGlovePermission.BLL.RGP_ModuleAuthorityList MAL = new RedGlovePermission.BLL.RGP_ModuleAuthorityList();
            DataSet MALDS = MAL.GetAuthorityList(ModuleID);
            DataSet ds = Abll.GetAuthorityList("", "order by AuthorityOrder asc");

            AuthorityNum.Text = ds.Tables[0].Rows.Count.ToString();
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                bool v = false;
                for (int k = 0; k < MALDS.Tables[0].Rows.Count; k++)
                {
                    if (MALDS.Tables[0].Rows[k]["AuthorityTag"].ToString() == ds.Tables[0].Rows[i]["AuthorityTag"].ToString())
                    {
                        v = true;
                        break;
                    } 
                }

                if (v)
                {
                    strState.Append("<tr><td width=\"80\">" + ds.Tables[0].Rows[i]["AuthorityName"]
                        + "</td><td width=\"100\"><table id=\"Alist" + i.ToString()
                        + "\" border=\"0\"><tr><td><input id=\"Alist" + i.ToString()
                        + "_0\" type=\"radio\" name=\"Alist" + i.ToString() + "\" value=\"1\" checked=\"checked\" />"
                        + "<label for=\"Alist" + i.ToString() + "_0\">允许</label></td><td>"
                        + "<input id=\"Alist" + i.ToString() + "_1\" type=\"radio\" name=\"Alist" + i.ToString() + "\" value=\"0\" />"
                        + "<label for=\"Alist" + i.ToString() + "_1\">拒绝</label></td></tr></table></td>");
                    strVerify.Append("1,");
                }
                else
                {
                    strState.Append("<tr><td width=\"80\">" + ds.Tables[0].Rows[i]["AuthorityName"]
                        + "</td><td width=\"100\"><table id=\"Alist" + i.ToString()
                        + "\" border=\"0\"><tr><td><input id=\"Alist" + i.ToString()
                        + "_0\" type=\"radio\" name=\"Alist" + i.ToString() + "\" value=\"1\" />"
                        + "<label for=\"Alist" + i.ToString() + "_0\">允许</label></td><td>"
                        + "<input id=\"Alist" + i.ToString() + "_1\" type=\"radio\" name=\"Alist" + i.ToString() + "\" value=\"0\" checked=\"checked\" />"
                        + "<label for=\"Alist" + i.ToString() + "_1\">拒绝</label></td></tr></table></td>");
                    strVerify.Append("0,");
                }                

                //写入标识
                strTag.Append("<input type=\"hidden\" name=\"Atag" + i.ToString() + "\" id=\"Atag" + i.ToString() + "\" value=\"" + ds.Tables[0].Rows[i]["AuthorityTag"] + "\" />");
            }
            strState.Append("</table>");
            strVerify.Append("\" />");
            divstate.InnerHtml = strState.ToString() + strTag.ToString() + strVerify.ToString();

            #endregion
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ModuleList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ModuleList.PageIndex = e.NewPageIndex;
            BindOrder(); //重新绑定GridView数据的函数 
        }

        /// <summary>
        /// 执行事件
        /// 删除操作
        /// 查看/编辑模块信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ModuleList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName.ToString())
            {
                case "Del":
                    if (bll.DeleteModule(int.Parse(e.CommandArgument.ToString())))
                    {
                        AddPanel.Visible = false;
                        BindOrder();
                        ScriptManager.RegisterClientScriptBlock(CustomPanel1, this.GetType(), "MsgBox", "alert('删除成功');", true);
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(CustomPanel1, this.GetType(), "MsgBox", "alert('删除失败!');", true);
                    }
                    break;
                case "EditView":
                    BindPermissionUpdate(int.Parse(e.CommandArgument.ToString()));
                    btn_save.Visible = false;
                    btn_update.Visible = true;
                    AddPanel.Visible = true;    
                    break;
            }
        }
        
        /// <summary>
        /// 数据绑定到表格
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ModuleList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)//判定当前的行是否属于datarow类型的行
            {
                //当鼠标放上去的时候 先保存当前行的背景颜色 并给附一颜色
                e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#ffffcd',this.style.fontWeight='';");
                //当鼠标离开的时候 将背景颜色还原的以前的颜色
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor,this.style.fontWeight='';");

                LinkButton btnDel = ((LinkButton)e.Row.FindControl("btn_del"));

                btnDel.Attributes.Add("onclick", "return confirm('您确认要删除该记录吗?')");
            }
        }

        /// <summary>
        /// 选择分类
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ModuleType_SelectedIndexChanged(object sender, EventArgs e)
        {
            clearTxt();
            AddPanel.Visible = false;
            BindOrder();
        }

        /// <summary>
        /// 新增模块
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_add_Click(object sender, EventArgs e)
        {
            clearTxt();
            BindPermission();
            btn_update.Visible = false;
            btn_save.Visible = true;
            AddPanel.Visible = true;
        }

        /// <summary>
        /// 清空输入框数据
        /// </summary>
        public void clearTxt()
        {
            txt_Name.Text = "";
            txt_tag.Text = "";
            txt_url.Text = "";
            txt_state.SelectedIndex = 0;
            txt_order.Text = "";
            txt_Description.Text = "";
        }

        /// <summary>
        /// 取消新增模块
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_cancel_Click(object sender, EventArgs e)
        {
            AddPanel.Visible = false;
        }

        /// <summary>
        /// 保存新增模块信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_save_Click(object sender, EventArgs e)
        {
            RedGlovePermission.BLL.RGP_ModuleAuthorityList MAL= new RedGlovePermission.BLL.RGP_ModuleAuthorityList();
            RedGlovePermission.Model.RGP_Modules model= new RedGlovePermission.Model.RGP_Modules();
            model.ModuleTypeID = int.Parse(ModuleType.SelectedValue);
            model.ModuleName = txt_Name.Text.Trim();
            model.ModuleTag = txt_tag.Text.Trim();
            model.ModuleURL = txt_url.Text.Trim();
            if (txt_state.SelectedValue == "0")
            { model.ModuleDisabled = true; }
            else
            { model.ModuleDisabled = true; }
            model.ModuleOrder = int.Parse(txt_order.Text.Trim());
            model.ModuleDescription = txt_Description.Text.Trim();

            if (IsMenu.SelectedValue == "0")
            { model.IsMenu = false; }
            else
            { model.IsMenu = true; }

            if (!bll.Exists(txt_tag.Text.Trim()))
            {
                int RowID = bll.CreateModule(model);//返回模块ID;
                if (RowID != 0)//添加OK
                {
                    ArrayList list = new ArrayList();//建立事务列表
                    int n = int.Parse(AuthorityNum.Text);
                    for (int i = 0; i < n; i++)
                    {
                        if (Request.Form["Alist" + i.ToString()].ToString() == "1")//如果允许则插入记录
                        {
                            string item = string.Empty;
                            item = item + RowID.ToString() + "|" + Request.Form["Atag" + i.ToString()].ToString();
                            list.Add(item);
                        }
                    }
                    //权限加入是否成功！
                    if (MAL.CreateAuthorityList(list))
                    {
                        clearTxt();
                        if (!Glist.Visible)Glist.Visible = true;
                        BindOrder();
                        AddPanel.Visible = false;
                        ScriptManager.RegisterClientScriptBlock(CustomPanel1, this.GetType(), "MsgBox", "alert('添加成功！')", true);
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(CustomPanel1, this.GetType(), "MsgBox", "alert('添加操作失败！')", true);
                    }
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(CustomPanel1, this.GetType(), "MsgBox", "alert('添加操作失败！')", true);
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(CustomPanel1, this.GetType(), "MsgBox", "alert('标识已经存在，请更换后重试！')", true);
            }
        }

        /// <summary>
        /// 更新模块信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_update_Click(object sender, EventArgs e)
        {
            RedGlovePermission.BLL.RGP_ModuleAuthorityList MAL = new RedGlovePermission.BLL.RGP_ModuleAuthorityList();
            RedGlovePermission.Model.RGP_Modules model = new RedGlovePermission.Model.RGP_Modules();
            model.ModuleID = int.Parse(M_ID.Text);
            model.ModuleTypeID = int.Parse(ModuleType.SelectedValue);
            model.ModuleName = txt_Name.Text.Trim();
            model.ModuleTag = txt_tag.Text.Trim();
            model.ModuleURL = txt_url.Text.Trim();            
            if (txt_state.SelectedValue == "0")
            { model.ModuleDisabled = false; }
            else
            { model.ModuleDisabled = true; }
            model.ModuleOrder = int.Parse(txt_order.Text.Trim());
            model.ModuleDescription = txt_Description.Text.Trim();
            if (IsMenu.SelectedValue == "0")
            { model.IsMenu = false; }
            else
            { model.IsMenu = true; }

            string[] vstr=Request.Form["verifystate"].Split(',');

            if (!bll.UpdateExists(model.ModuleID, model.ModuleTag))
            {
                if (bll.UpdateModule(model))
                {
                    ArrayList list = new ArrayList();//建立事务列表
                    int n = int.Parse(AuthorityNum.Text);
                    for (int i = 0; i < n; i++)
                    {
                        //判断权限是否有变化
                        if (vstr[i] != Request.Form["Alist" + i.ToString()].ToString())
                        {
                            string item = string.Empty;
                            item = item + model.ModuleID.ToString() + "|"
                                + Request.Form["Atag" + i.ToString()].ToString() + "|"
                                + Request.Form["Alist" + i.ToString()].ToString();//判断插入增加还是删除
                            list.Add(item);
                        }
                    }
                    //权限更新是否成功！
                    if (MAL.UpdateAuthorityList(list))
                    {
                        BindPermissionUpdate(model.ModuleID);
                        BindOrder();
                        ScriptManager.RegisterClientScriptBlock(CustomPanel1, this.GetType(), "MsgBox", "alert('更新成功！')", true);
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(CustomPanel1, this.GetType(), "MsgBox", "alert('更新操作失败！')", true);
                    }
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(CustomPanel1, this.GetType(), "MsgBox", "alert('更新操作失败！')", true);
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(CustomPanel1, this.GetType(), "MsgBox", "alert('标识已经存在，请更换后重试！')", true);
            }
        }
    }
}
