namespace FineUIPro.Web.common.SysManage
{
    using BLL;
    using BLL.Common;
    using Model;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using System.Linq;

    public partial class UserList : PageBase
    {
        #region 加载
        /// <summary>
        /// 加载页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            // 表头过滤
            FilterDataRowItem = FilterDataRowItemImplement;
            if (!IsPostBack)
            {
                GetButtonPower();//权限设置
                btnNew.OnClientClick = Window1.GetShowReference("UserListEdit.aspx") + "return false;";
                btnDelete.OnClientClick = Grid1.GetNoSelectionAlertReference("Please select at least one item!");
                btnDelete.ConfirmText = String.Format("Are you sure you want to delete the selected &nbsp;<b><script>{0}</script></b>&nbsp; rows?", Grid1.GetSelectedCountReference());

                ddlPageSize.SelectedValue = Grid1.PageSize.ToString();
                // 绑定表格
                BindGrid();
            }
            else if (GetRequestEventArgument() == "FilterChange")
            {
                BindGrid();
            }
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindGrid()
        {
            string strSql = @"SELECT u.UserId,u.Account,u.UserCode,u.UserName,u.ChineseName,u.RoleId,
                                     r.RoleName,u.Phone,u.DepartId,dep.DepartName,u.Email,
                                     (CASE WHEN u.IsPost = 1 THEN 'On duty' ELSE 'Not on duty' END) AS IsPost, 
                                     u.Remark
                                FROM Sys_User AS u
                                LEFT JOIN dbo.Sys_Role AS r ON r.RoleId = u.RoleId
                                LEFT JOIN dbo.Base_Depart AS dep ON dep.DepartId = u.DepartId
                                where UserId != @UserId";

            List<SqlParameter> listStr = new List<SqlParameter>();
            listStr.Add(new SqlParameter("@UserId", Const.GlyId));
            if (!string.IsNullOrEmpty(this.txtUserName.Text.Trim()))
            {
                strSql += " AND u.UserName LIKE @userName";
                listStr.Add(new SqlParameter("@userName", "%" + this.txtUserName.Text.Trim() + "%"));
            }
            if (!string.IsNullOrEmpty(this.txtAccount.Text.Trim()))
            {
                strSql += " AND u.Account LIKE @Account";
                listStr.Add(new SqlParameter("@Account", "%" + this.txtAccount.Text.Trim() + "%"));
            }
            if (!string.IsNullOrEmpty(this.txtDepartName.Text.Trim()))
            {
                strSql += " AND dep.DepartName LIKE @DepartName";
                listStr.Add(new SqlParameter("@DepartName", "%" + this.txtDepartName.Text.Trim() + "%"));
            }
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);

            // 2.获取当前分页数据
            //var table = this.GetPagedDataTable(Grid1, tb1);
            Grid1.RecordCount = tb.Rows.Count;
            tb = GetFilteredTable(Grid1.FilteredData, tb);
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        #endregion

        protected void Text_TextChanged(object sender, EventArgs e)
        {
            BindGrid();
        }

        #region 过滤表头
        /// <summary>
        /// 过滤表头
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_FilterChange(object sender, EventArgs e)
        {
            BindGrid();
        }

        /// <summary>
        /// 根据表头信息过滤列表数据
        /// </summary>
        /// <param name="sourceObj"></param>
        /// <param name="fillteredOperator"></param>
        /// <param name="fillteredObj"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        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" && sourceValue == fillteredValue)
                {
                    valid = true;
                }
                else if (fillteredOperator == "contain" && sourceValue.Contains(fillteredValue))
                {
                    valid = true;
                }
            }
            if (column == "UnitCode")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal" && sourceValue == fillteredValue)
                {
                    valid = true;
                }
                else if (fillteredOperator == "contain" && sourceValue.Contains(fillteredValue))
                {
                    valid = true;
                }
            }
            if (column == "UnitName")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal" && sourceValue == fillteredValue)
                {
                    valid = true;
                }
                else if (fillteredOperator == "contain" && sourceValue.Contains(fillteredValue))
                {
                    valid = true;
                }
            }
            if (column == "ChineseName")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal" && sourceValue == fillteredValue)
                {
                    valid = true;
                }
                else if (fillteredOperator == "contain" && sourceValue.Contains(fillteredValue))
                {
                    valid = true;
                }
            }

            if (column == "IsPost")
            {
                string sourceValue = sourceObj.ToString();
                string fillteredValue = fillteredObj.ToString();
                if (fillteredOperator == "equal" && sourceValue == fillteredValue)
                {
                    valid = true;
                }
            }
            return valid;
        }
        #endregion

        #region  删除数据
        /// <summary>
        /// 批量删除数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            DeleteData();
        }

        /// <summary>
        /// 右键删除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMenuDelete_Click(object sender, EventArgs e)
        {
            this.DeleteData();
        }

        /// <summary>
        /// 删除方法
        /// </summary>
        private void DeleteData()
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    if (judgementDelete(rowID))
                    {
                        BLL.Sys_LogService.DeleteLogByUserId(rowID);
                        BLL.Sys_UserService.DeleteUserById(rowID);
                    }
                }
                BindGrid();
                BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Delete user information!");
                ShowNotify("Deleted successfully!");
            }
        }

        #endregion

        #region 分页、排序
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        /// <summary>
        /// 分页显示条数下拉框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }

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

        #region 关闭窗口
        /// <summary>
        /// 关闭弹出窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Window1_Close(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion

        #region 编辑
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInParent("Please select at least one record!");
                return;
            }
            string Id = Grid1.SelectedRowID;
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("UserListEdit.aspx?userId={0}", Id, "编辑 - ")));
        }

        /// <summary>
        /// Grid行双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            btnEdit_Click(null, null);
        }

        /// <summary>
        /// 右键编辑事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnMenuEdit_Click(object sender, EventArgs e)
        {
            btnEdit_Click(null, null);
        }
        #endregion

        #region 判断是否可删除

        /// <summary>
        /// 判断是否可以删除
        /// </summary>
        /// <returns></returns>
        private bool judgementDelete(string userId)
        {
            string content = "";
            
            //if (BLL.Common_NoticeService.GetNoticeCountByUserId(userId) > 0)
            //{
            //    content = "通知中已经使用了该用户,不能删除!";
            //}
            //if (Funs.DB.Project_User.FirstOrDefault(x=>x.UserId == userId) != null)
            //{
            //    content = "项目设置参与用户已经使用了该用户,不能删除!";
            //}

            if (content == "")
            {
                return true;
            }
            else
            {
                ShowNotify(content);
                return false;
            }
        }
        #endregion

        #region 权限设置
        /// <summary>
        /// 菜单按钮权限
        /// </summary>
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.UserId, BLL.Const.UserMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    this.btnNew.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnEdit.Hidden = false;
                    this.btnMenuEdit.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnDelete.Hidden = false;
                    this.btnMenuDelete.Hidden = false;
                }
            }
        }
        #endregion

        #region 导入
        #region 定义项
        /// <summary>
        /// 上传预设的虚拟路径
        /// </summary>
        private string initPath = Const.ExcelUrl;

        /// <summary>
        /// 错误集合
        /// </summary>
        public static string errorInfos = string.Empty;
        #endregion

        #region 模板下载
        /// <summary>
        /// 模板下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Confirm.GetShowReference("Are you sure to download the import template?", String.Empty, MessageBoxIcon.Question, PageManager1.GetCustomEventReference(false, "Confirm_OK"), PageManager1.GetCustomEventReference("Confirm_Cancel")));
        }

        /// <summary>
        /// 下载导入模板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void PageManager1_CustomEvent(object sender, CustomEventArgs e)
        {
            if (e.EventArgument == "Confirm_OK")
            {
                string rootPath = Server.MapPath("~/");
                string uploadfilepath = rootPath + Const.UserTemplateUrl;
                string filePath = Const.UserTemplateUrl;
                string fileName = Path.GetFileName(filePath);
                FileInfo info = new FileInfo(uploadfilepath);
                long fileSize = info.Length;
                Response.ClearContent();
                Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                Response.ContentType = "excel/plain";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.AddHeader("Content-Length", fileSize.ToString().Trim());
                Response.TransmitFile(uploadfilepath, 0, fileSize);
                Response.End();
            }
        }
        #endregion

        #region 导入
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnImport_Click(object sender, EventArgs e)
        {
            string message = string.Empty;
            errorInfos = string.Empty;
            List<Sys_User> userList = new List<Sys_User>();
            try
            {
                if (this.fuAttachUrl.HasFile == false)
                {
                    ShowNotify("Please select Excel file!", MessageBoxIcon.Warning);
                    return;
                }
                string IsXls = Path.GetExtension(this.fuAttachUrl.FileName).ToString().Trim().ToLower();
                if (IsXls != ".xls" && IsXls != ".xlsx")
                {
                    ShowNotify("Only Excel files can be selected!", MessageBoxIcon.Warning);
                    return;
                }
                if (userList != null)
                {
                    userList.Clear();
                }
                if (!string.IsNullOrEmpty(errorInfos))
                {
                    errorInfos = string.Empty;
                }
                string rootPath = Server.MapPath("~/");
                string initFullPath = rootPath + initPath;
                if (!Directory.Exists(initFullPath))
                {
                    Directory.CreateDirectory(initFullPath);
                }
                //指定上传文件名称
                this.hdFileName.Text = BLL.Funs.GetNewFileName() + IsXls;
                //上传文件路径
                string filePath = initFullPath + this.hdFileName.Text;
                //文件上传服务器
                this.fuAttachUrl.PostedFile.SaveAs(filePath);
                //文件上传服务器后的名称
                string fileName = rootPath + initPath + this.hdFileName.Text;
                //读取Excel
                DataSet ds = NPOIHelper.ExcelToDataSet(fileName, out errorInfos, true);
                //验证Excel读取是否有误
                if (!string.IsNullOrEmpty(errorInfos))
                {
                    ShowNotify(errorInfos, MessageBoxIcon.Warning);
                    return;
                }
                //导入数据库
                var departs = (from x in Funs.DB.Base_Depart select x).ToList();

                if (ds.Tables.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        Sys_User u = new Sys_User();

                        #region 数据验证和赋值
                        string BGDID = ds.Tables[0].Rows[i]["BGDID"].ToString();
                        if (BGDID != null && !string.IsNullOrEmpty(BGDID))
                        {
                            u.Account = BGDID;
                        }
                        else
                        {
                            errorInfos += (i + 2) + "Line, [BGDID] cannot be empty!</br>";
                        }
                        string Section = ds.Tables[0].Rows[i]["Section"].ToString();
                        if (Section != null && !string.IsNullOrEmpty(Section))
                        {
                            u.DepartId = Section;
                        }
                        else
                        {
                            errorInfos += (i + 2) + "Line, [Section] cannot be empty!</br>";
                        }
                        u.ChineseName = ds.Tables[0].Rows[i]["Name(CN)"].ToString();
                        u.Email = ds.Tables[0].Rows[i]["Mail"].ToString();
                        u.Address = ds.Tables[0].Rows[i]["Location"].ToString();
                        userList.Add(u);
                        #endregion
                    }
                    if (!string.IsNullOrEmpty(errorInfos))
                    {
                        ShowNotify(errorInfos, MessageBoxIcon.Warning, 10000);
                        return;
                    }
                    if (userList.Count > 0)
                    {
                        foreach (var item in userList)
                        {
                            string departId = string.Empty;
                            var dep = departs.Where(x => x.DepartCode == item.DepartId).FirstOrDefault();
                            if (dep == null)
                            {
                                Model.Base_Depart newDepart = new Base_Depart();
                                departId = SQLHelper.GetNewID(typeof(Model.Base_Depart));
                                newDepart.DepartId = departId;
                                newDepart.DepartCode = item.DepartId;
                                newDepart.DepartName = item.DepartId;
                                BLL.DepartService.AddDepart(newDepart);
                            }

                            var user = BLL.Sys_UserService.GetUserByAccount(item.Account);
                            if (user != null)
                            {
                                user.DepartId = departId;
                                user.ChineseName = item.ChineseName;
                                user.Email = item.Email;
                                user.Address = item.Address;
                                BLL.Sys_UserService.UpdateUserList(user);
                            }
                            else
                            {
                                Model.Sys_User newUser = new Sys_User();
                                newUser.UserId = SQLHelper.GetNewID(typeof(Model.Sys_User));
                                newUser.Account = item.Account;
                                newUser.UserName = item.UserName;
                                newUser.DepartId = departId;
                                newUser.ChineseName = item.ChineseName;
                                newUser.Password = Sys_UserService.GetEncryptionPassword(newUser.Account);
                                newUser.RoleId = BLL.Const.Role_CommonUsers;
                                newUser.IsPost = true;
                                newUser.Email = item.Email;
                                newUser.Address = item.Address;
                                BLL.Sys_UserService.AddUser(newUser);
                            }
                        }
                    }
                    ShowNotify("Import success!", MessageBoxIcon.Success);
                    PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
                }
                else
                {
                    ShowAlert("No data!", MessageBoxIcon.Warning);
                    return;
                }
            }
            catch (Exception ex)
            {
                ShowAlert("'" + ex.Message + "'", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #endregion
    }
}