using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Entity;
using BLL;

public partial class Admin_System_ModUser : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        RoleCheck.DenyLogin();
        if (!IsPostBack)
            BindUserInfo();
    }

    private string userID
    {
        get { return Request.QueryString["userID"]; }
    }

    private void BindUserInfo()
    {
        hfdUserID.Value = userID;

        Entity.User user = new BLLAdmin().GetUserByID(userID);
        if (user != null)
        {
            txtUserID.Text = user.UserID;
            txtName.Text = user.Name;
            drlDeptList.SelectedValue = user.Department.DeptID.ToString();
            rblLocked.SelectedValue = user.Locked.ToString();
            foreach (string right in user.RightList)
            {
                for (int i = 0; i < cblRight.Items.Count; i++ )
                {
                    if (right.Equals(cblRight.Items[i].Text))
                    {
                        cblRight.Items[i].Selected = true;
                        break;
                    }
                }
            }

            if (BLLAdmin.DEFAULT_ADMIN.Equals(user.UserID.ToLower()))
                lblAdminMsg.Visible = true;
            else
                lblAdminMsg.Visible = false;
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        //----------验证信息
        if (drlDeptList.SelectedIndex == 0)
        {
            lblMsg.Text = "请选择部门！";
            return;
        }

        bool hasSelectRight = false;
        for (int i = 0; i < cblRight.Items.Count; i++)
            if (cblRight.Items[i].Selected)
            {
                hasSelectRight = true;
                break;
            }
        if (!hasSelectRight)
        {
            lblMsg.Text = "请选择权限！";
            return;
        }

        Entity.User user = new User();
        user.UserID = txtUserID.Text;
        user.Name = txtName.Text;
        user.Department.DeptID = Convert.ToInt16(drlDeptList.SelectedItem.Value);

        List<string> rightList = new List<string>();
        for (int i = 0; i < cblRight.Items.Count; i++)
            if (cblRight.Items[i].Selected)
                rightList.Add(cblRight.Items[i].Text);
        user.RightList = rightList;

        user.Locked = rblLocked.SelectedIndex == 0 ? true : false;

        try
        {
            new BLLAdmin().ModifyUser(user);
            Response.Redirect("userList.aspx");
        }
        catch(BLLException error)
        {
            lblMsg.Text = error.Msg;
        }
    }
}
