using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using Newtonsoft.Json.Linq;
namespace FineUIPro.Web.OfficeCheck.Inspect
{
    public partial class SafetyInspection : PageBase
    {
        public Model.SGGLDB db = Funs.DB;
        #region 定义变量
        /// 
        /// 项目主键
        /// 
        public string ProjectId
        {
            get
            {
                return (string)ViewState["ProjectId"];
            }
            set
            {
                ViewState["ProjectId"] = value;
            }
        }
        #endregion
        
        #region 页面加载
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) {
                GetButtonPower();
                Funs.DropDownPageSize(this.ddlPageSize);
                this.ddlPageSize.SelectedValue = this.Grid1.PageSize.ToString();
                InitTreeMenu();
            }
        }
        #endregion
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            if (this.CurrUser != null)
            {
                var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.SafetyInspectionMenuId);
                if (buttonList.Count() > 0)
                {
                    if (buttonList.Contains(BLL.Const.BtnAdd))
                    {
                        this.btnNew.Hidden = false;
                    }
                    if (buttonList.Contains(BLL.Const.BtnModify))
                    {
                        this.btnMenuEdit.Hidden = false;
                    }
                    if (buttonList.Contains(BLL.Const.BtnDelete))
                    {
                        //this.btnDelete.Hidden = false;
                        this.btnMenuDelete.Hidden = false;
                    }
                }
            }
        }
        #endregion
        #region 加载树
        /// 
        /// 加载树
        /// 
        private void InitTreeMenu()
        {
            this.trProjects.Nodes.Clear();
            this.trProjects.ShowBorder = false;
            this.trProjects.ShowHeader = false;
            this.trProjects.EnableIcons = true;
            this.trProjects.AutoScroll = true;
            this.trProjects.EnableSingleClickExpand = true;
            //默认加载
            TreeNode node = new TreeNode();
            node.Text = "全部";
            node.NodeID = "1";
            node.CommandName = "all";
            node.EnableClickEvent = true;
            node.EnableExpandEvent = true;
            node.Expanded = true;
            this.trProjects.Nodes.Add(node);
            var list = BLL.ProjectService.GetProjectWorkList();
            if (list.Count() > 0)
            {
                foreach (var item in list)
                {
                    var Snode = new TreeNode();
                    Snode.Text = item.ProjectName;
                    Snode.NodeID = item.ProjectId;
                    Snode.CommandName = "parent";
                    Snode.EnableClickEvent = true;
                    Snode.EnableExpandEvent = true;
                    Snode.Expanded = true;
                    node.Nodes.Add(Snode);
                }
            }
        }
        #endregion
        #region  Tree点击事件
        /// 
        /// Tree点击事件
        /// 
        /// 
        /// 
        protected void trProjects_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            this.BindGrid();
        }
        #endregion
        #region 加载数据
        private void BindGrid()
        {
            string strSql =
                @"select Inspection.InspectionId,Inspection.InspectionCode,Inspection.ProjectId,b.UserName as PersonResponsible,Inspection.InspectTime,Inspection.Description,"
                + @" (CASE WHEN Inspection.States ='1' THEN '待整改' 
                              WHEN Inspection.States ='2' THEN '待评价' 
                              WHEN Inspection.States ='3' THEN '部分完成' 
                              WHEN Inspection.States ='4' THEN '待复查' 
                              WHEN Inspection.States ='5' THEN '已完成' 
                                ELSE '专项检查' END) AS States, "
                + @" c.UserName as InspectMan,Inspection.InspectType,Inspection.InspectItemSetId  from Inspect_Inspection Inspection left join Sys_User b on Inspection.PersonResponsible = b.UserID left join Sys_User c on Inspection.InspectMan  = c.UserID where Inspection.InspectType='1' ";
                          
            
            List listStr = new List();
            if (this.trProjects.SelectedNode != null)
            {
                strSql += " AND Inspection.ProjectId = @ProjectId";
                listStr.Add(new SqlParameter("@ProjectId", this.trProjects.SelectedNode.NodeID));
            }
            if (!string.IsNullOrEmpty(txtPersonResponsible.Text.Trim()))
            {
                strSql += " AND b.UserName like @PersonResponsible"; 
                listStr.Add(new SqlParameter("@PersonResponsible", "%" + txtPersonResponsible.Text.Trim() + "%"));
            }
            // if (this.rbStates.SelectedValue!="-1")
            // {
            //     strSql += " AND Inspection.States = @States"; 
            //     listStr.Add(new SqlParameter("@States", this.rbStates.SelectedValue));
            // }
            
            if (!string.IsNullOrEmpty(this.txtStartTime.Text.Trim()))
            {
                strSql += " AND Inspection.InspectTime >= @StartTime";
                listStr.Add(new SqlParameter("@StartTime", this.txtStartTime.Text.Trim()));
            }
            if (!string.IsNullOrEmpty(this.txtEndTime.Text.Trim()))
            {
                strSql += " AND Inspection.InspectTime <= @EndTime";
                listStr.Add(new SqlParameter("@EndTime", this.txtEndTime.Text.Trim()));
            }
            strSql += " order by Inspection.InspectTime desc";
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            //if (tb != null)
            //{
            //    foreach (DataRow row in tb.Rows)
            //    {
            //        if (!string.IsNullOrEmpty(row["InspectionCode"].ToString()))
            //        {
            //            row["index"] = int.Parse(System.Text.RegularExpressions.Regex.Replace(row["InspectionCode"].ToString(), @"[^0-9]+", ""));
            //        }
            //    }
            //}
            Grid1.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        #endregion
        #region  修改关闭窗口
        /// 
        /// 关闭窗口
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            ShowNotify("操作成功!", MessageBoxIcon.Success);
            this.BindGrid();
        }
        protected void Window2_Close(object sender, WindowCloseEventArgs e)
        {
            ShowNotify("增加成功!", MessageBoxIcon.Success);
            this.BindGrid();
        }
        #endregion
        #region 新增
        protected void btnNew_Click(object sender, EventArgs e) {
            if (trProjects.SelectedNode==null)
            {
                ShowNotify("请选择子节点进行添加!", MessageBoxIcon.Warning);
                return;
            }
            if (trProjects.SelectedNode.CommandName == "parent")
            {
                PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("SafetyInspectionEdit.aspx?ProjectId={0}",trProjects.SelectedNode.NodeID ,"增加 - ")));
            }
            else {
                ShowNotify("请选择子节点进行添加!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        /// 
        /// 编辑按钮
        /// 
        /// 
        /// 
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            Debug.WriteLine(this.Grid1.SelectedRowID);
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("SafetyInspectionEdit.aspx?InspectionId={0}", this.Grid1.SelectedRowID, "编辑 - ")));
        }
        /// 
        /// Grid行双击事件
        /// 
        /// 
        /// 
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            this.btnEdit_Click(null, null);
        }
        /// 
        /// 批量删除
        /// 
        /// 
        /// 
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    BLL.OfficeCheck.Inspect.Inspect_InspectionService.DeleteInspectionById(rowID);
                }
                BindGrid();
                ShowNotify("删除数据成功!", MessageBoxIcon.Success);
            }
        }
        #region 导出按钮
        /// 导出按钮
        /// 
        /// 
        /// 
        protected void btnOut_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            string name = this.trProjects.SelectedNode.Text;
            string filename = Funs.GetNewFileName();
            Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(name + filename, System.Text.Encoding.UTF8) + ".xls");
            Response.ContentType = "application/excel";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            this.Grid1.PageSize = this.Grid1.RecordCount;
            this.BindGrid();
            Response.Write(GetGridTableHtml(Grid1));
            Response.End();
        }
        #endregion
        
        
        #region 查询
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txtStartTime.Text.Trim()) && !string.IsNullOrEmpty(this.txtEndTime.Text.Trim()))
            {
                if (Funs.GetNewDateTime(this.txtStartTime.Text.Trim()) > Funs.GetNewDateTime(this.txtEndTime.Text.Trim()))
                {
                    Alert.ShowInTop("开始时间不能大于结束时间!", MessageBoxIcon.Warning);
                    return;
                }
            }
            this.BindGrid();
        }
        #endregion
        
        
        #region GV 数据操作
        /// 
        /// 分页
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            this.Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            this.BindGrid();
        }
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            this.Grid1.SortDirection = e.SortDirection;
            this.Grid1.SortField = e.SortField;
            this.BindGrid();
        }
        /// 
        /// 分页显示条数下拉框
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            this.BindGrid();
        }
        #endregion
    }
}