using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using BLL;

namespace FineUIPro.Web.common.ProjectSet
{
    public partial class SelectUser : PageBase
    {
        #region 定义变量
        /// <summary>
        ///  项目id
        /// </summary>
        public string ProjectId
        {
            get
            {
                return (string)ViewState["ProjectId"];
            }
            set
            {
                ViewState["ProjectId"] = value;
            }
        }
        #endregion

        #region 加载
        protected void Page_Load(object sender, EventArgs e)
        {
            // 表头过滤
            FilterDataRowItem = FilterDataRowItemImplement;

            if (!IsPostBack)
            {
                this.ProjectId = Request.Params["projectId"]; 
                InitTreeMenu();//加载树
            }
        }

        private void BindGrid()
        {
            string unitid = this.tvUnit.SelectedNodeID;

            string strSql = @"select UserId,Account,UserCode,UserName,RoleIds 
                                from dbo.Sys_User 
                               where IsPost=1 and UnitId=@UnitId";

            List<SqlParameter> listStr = new List<SqlParameter>();
            listStr.Add(new SqlParameter("@UnitId", unitid));
           
            strSql += " order by UserName";
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);

            tb = GetFilteredTable(Grid1.FilteredData, tb);
            Grid1.DataSource = tb;
            Grid1.DataBind();

            var pUser = BLL.Project_UserService.GetUserByProjectIdUnitId(this.ProjectId, unitid);
            if (pUser!=null)
            {
                string[] arr = new string[pUser.Count()];
                int i = 0;
                foreach (var q in pUser)
                {
                    arr[i] = q.UserId;
                    i++;
                }
                Grid1.SelectedRowIDArray = arr;
            }
        }
        #endregion

        #region 表头过滤
        protected void Grid1_FilterChange(object sender, EventArgs e)
        {
            BindGrid();
        }

        private bool FilterDataRowItemImplement(object sourceObj, string fillteredOperator, object fillteredObj, string column)
        {
            bool valid = false;
            if (column == "UserName")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal")
                {
                    if (sourceValue == fillteredValue)
                    {
                        valid = true;
                    }
                }
                else if (fillteredOperator == "contain")
                {
                    if (sourceValue.Contains(fillteredValue))
                    {
                        valid = true;
                    }
                }
            }

            else if (column == "Account")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal")
                {
                    if (sourceValue == fillteredValue)
                    {
                        valid = true;
                    }
                }
                else if (fillteredOperator == "contain")
                {
                    if (sourceValue.Contains(fillteredValue))
                    {
                        valid = true;
                    }
                }
            }
            return valid;
        }

        #endregion

        #region
        /// <summary>
        /// 加载树
        /// </summary>
        private void InitTreeMenu()
        {
            this.tvUnit.Nodes.Clear();
            var projectUnits = from x in Funs.DB.Project_Unit
                               where x.ProjectId == this.ProjectId
                               orderby x.UnitType descending
                               select x;
            if (projectUnits.Count() > 0)
            {
                foreach (var item in projectUnits)
                {
                    var baseUnit = Funs.DB.Base_Unit.FirstOrDefault(x => x.UnitId == item.UnitId);
                   
                    TreeNode rootNode = new TreeNode();//定义根节点
                    rootNode.Text = baseUnit.UnitName;
                    rootNode.NodeID = item.UnitId;
                    rootNode.EnableClickEvent = true;
                    this.tvUnit.Nodes.Add(rootNode);
                }
            }
        }
        #endregion

        #region 点击TreeView
        /// <summary>
        /// 点击TreeView
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void tvUnit_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            if (!string.IsNullOrEmpty(this.tvUnit.SelectedNode.NodeID))
            {
                BindGrid();
            }
        }
        #endregion

        #region 编辑
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            if (CommonService.GetAllButtonPowerList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.ProjectUserMenuId, Const.BtnSave))
            {
                string coutValue = IsSave();
                if (!string.IsNullOrEmpty(coutValue))
                {
                    ShowNotify(coutValue + Resources.Lan.PleaseSelectRole);
                }

                else
                {
                    BLL.Project_UserService.DeleteProject_UserByProjectId(this.ProjectId, this.tvUnit.SelectedNode.NodeID);
                    //int[] fff = Grid1.SelectedRowIndexArray;

                    string[] selectRowId = Grid1.SelectedRowIDArray;
                    int n = 0;
                    int j = 0;
                    int[] selections = new int[selectRowId.Count()];
                    foreach (GridRow row in Grid1.Rows)
                    {
                        if (selectRowId.Contains(row.DataKeys[0]))
                        {
                            selections[n] = j;
                            n++;
                        }
                        j++;
                    }

                    var select = selections.Distinct();
                    foreach (int i in select)
                    {
                        //System.Web.UI.WebControls.DropDownList ddlRole = (System.Web.UI.WebControls.DropDownList)Grid1.Rows[i].FindControl("ddlRole");
                        System.Web.UI.WebControls.CheckBoxList cblRoles = (System.Web.UI.WebControls.CheckBoxList)Grid1.Rows[i].FindControl("cblRoles");
                        string roles = string.Empty;

                        Model.Project_User newUser = new Model.Project_User();
                        newUser.ProjectId = this.ProjectId;
                        newUser.UserId = Grid1.DataKeys[i][0].ToString();
                        newUser.IsPost = true;
                        if (!string.IsNullOrEmpty(cblRoles.SelectedValue))
                        {
                            foreach (System.Web.UI.WebControls.ListItem item in cblRoles.Items)
                            {
                                if (item.Selected)
                                {
                                    roles += item.Value + ",";
                                }
                            }
                            if (!string.IsNullOrEmpty(roles))
                            {
                                roles = roles.Substring(0, roles.LastIndexOf(","));
                                newUser.RoleIds = roles;
                                BLL.Project_UserService.AddProject_User(newUser);
                            }

                        }
                    }
                    BLL.Sys_LogService.AddLog(Const.System_1, this.CurrUser.LoginProjectId, this.CurrUser.UserId, Const.ProjectUserMenuId, Const.BtnSave, "");
                    PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
                }
            }
            else
            {
                ShowNotify(Resources.Lan.NoPrivilegePrompt);
            }
        }
        #endregion

        #region 排序
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid();
        }
        #endregion

        #region Grid行绑定事件
        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            System.Web.UI.WebControls.CheckBoxList cblRoles = (System.Web.UI.WebControls.CheckBoxList)Grid1.Rows[e.RowIndex].FindControl("cblRoles");
            string projectId = Request.Params["projectId"];

            cblRoles.DataTextField = "RoleName";
            cblRoles.DataValueField = "RoleId";
            cblRoles.DataSource = BLL.Sys_RoleService.GetRoleList();
            cblRoles.DataBind();

            var roles = BLL.Project_UserService.GetProject_UserByProjectIdUserId(projectId, e.RowID);
            if (roles != null)
            {
                // 单位类型下拉框
                if (!string.IsNullOrEmpty(roles.RoleIds))
                {
                    List<string> roleList = roles.RoleIds.Split(',').ToList();
                    foreach (var role in roleList)
                    {
                        for (int i = 0; i < cblRoles.Items.Count; i++)
                        {
                            if (cblRoles.Items[i].Value == role)
                            {
                                cblRoles.Items[i].Selected = true;
                            }
                        }
                    }
                }
            }
            else
            {
                var user = BLL.Sys_UserService.GetUsersByUserId(e.RowID);
                if (user!=null && !string.IsNullOrEmpty(user.RoleIds))
                {
                    List<string> roleList = user.RoleIds.Split(',').ToList();
                    foreach (var role in roleList)
                    {
                        for (int i = 0; i < cblRoles.Items.Count; i++)
                        {
                            if (cblRoles.Items[i].Value == role)
                            {
                                cblRoles.Items[i].Selected = true;
                            }
                        }
                    }
                }
            }
        }
        #endregion

        #region 验证是否选择角色
        /// <summary>
        /// 验证是否选择角色
        /// </summary>
        /// <returns></returns>
        protected string IsSave()
        {
            string coutValue = string.Empty;
            //int[] selections = Grid1.SelectedRowIndexArray;
            string[] selectRowId = Grid1.SelectedRowIDArray;
            int n = 0;
            int j = 0;
            int[] selections = new int[selectRowId.Count()];
            foreach (GridRow row in Grid1.Rows)
            {
                if (selectRowId.Contains(row.DataKeys[0]))
                {
                    selections[n] = j;
                    n++;
                }
                j++;
            }
            foreach (int i in selections)
            {
                System.Web.UI.WebControls.CheckBoxList cblRoles = (System.Web.UI.WebControls.CheckBoxList)Grid1.Rows[i].FindControl("cblRoles");
                if (string.IsNullOrEmpty(cblRoles.SelectedValue))
                {
                    coutValue += Resources.Lan.Line + ":" + (n + 1).ToString();
                }
            }
            return coutValue;
        }
        #endregion

    }
}