using BLL;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.PZHGL.GJSX
{
    public partial class GJSXFind : PageBase
    {
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //责任单位
                UnitService.InitUnitDropDownList(this.DropUnitId, this.CurrUser.LoginProjectId, false);
                //专业
                CNProfessionalService.InitCNProfessional(this.DropCNProfessional_ID, false);
                //编号
                string projectCode = BLL.ProjectService.GetProjectCodeByProjectId(this.CurrUser.LoginProjectId);
                //紧急程度
                QuestionTypeService.InitQuestionTypeDropDownList(this.DropQuestionTypeID, false);
                //事项类别
                GJSXTypeService.InitGJSXTypeDropDownList(this.DropGJSXTypeID, false);
                //验收人
                UserService.InitUserDropDownList(DropUser_ReceiveID, CurrUser.LoginProjectId, false, string.Empty);
                //接收人
                UserService.InitUserDropDownList(DropUser_Acceptance, CurrUser.LoginProjectId, false, string.Empty);
                //提出人
                UserService.InitUserDropDownList(DropUserId, CurrUser.LoginProjectId, false, string.Empty);
                Funs.DropDownPageSize(this.ddlPageSize);
                ////权限按钮方法
                this.GetButtonPower();
                //this.btnNew.OnClientClick = Window1.GetShowReference("GJSXListEdit.aspx?EditType=add") + "return false;";
                if (this.CurrUser != null && this.CurrUser.PageSize.HasValue)
                {
                    Grid1.PageSize = this.CurrUser.PageSize.Value;
                }
                this.ddlPageSize.SelectedValue = Grid1.PageSize.ToString();
                // 绑定表格
                this.BindGrid();
            }
        }
        /// 
        /// 绑定数据
        /// 
        private void BindGrid()
        {
            DataTable tb = BindData();
            Grid1.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
            try
            {
                for (int i = 0; i < Grid1.Rows.Count; i++)
                {
                    var state = tb.Rows[i]["state"].ToString().Trim();
                    var completeDate = tb.Rows[i]["CompleteDate"].ToString();
                    DateTime dtCompleteDate = Convert.ToDateTime(completeDate);
                    if (Grid1.Rows[i].DataKeys[0] != null && !string.IsNullOrWhiteSpace(state))
                    {
                        if (state == "0")
                        {
                            Grid1.Rows[i].CellCssClasses[6] = "green";
                        }
                        else if (state == "2" || state == "3")
                        {
                            Grid1.Rows[i].CellCssClasses[6] = "blue";
                        }
                        else if (state == "4")
                        {
                            Grid1.Rows[i].CellCssClasses[6] = "red";
                        }
                    }
                }
            }
            catch (Exception ex) { }
        }
        /// 
        /// 数据加载
        /// 
        /// 
        private DataTable BindData()
        {
            string strSql = " AND state in (0,2,3,4) ";
            List listStr = new List();
            if (!string.IsNullOrEmpty(Request.Params["projectId"]))  ///是否文件柜查看页面传项目值
            {
                listStr.Add(new SqlParameter("@ProjectId", Request.Params["projectId"]));
            }
            else
            {
                listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            }
            if (this.state.SelectedItemArray.Count() > 0)
            {//状态
                var stateList = String.Join(", ", this.state.SelectedValueArray).Split(',');
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in stateList)
                {
                    //if (!string.IsNullOrEmpty(item) && item != BLL.Const._Null && item != "4")
                    //{
                    strSql += $" OR state = '{item}' ";
                    //}
                    //else if (item == "4")
                    //{
                    //    strSql += " OR (state <> '0' and getdate() > DATEADD(day, 1, CompleteDate)) ";
                    //}
                    i++;
                }
                strSql += ")";
            }
            if (this.DropUserId.SelectedItemArray.Count() > 1 || (this.DropUserId.SelectedValue != BLL.Const._Null && this.DropUserId.SelectedItemArray.Count() == 1))
            {//提出人
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in this.DropUserId.SelectedItemArray)
                {
                    if (!string.IsNullOrEmpty(item.Text) && item.Text != BLL.Const._Null)
                    {
                        strSql += $" OR username = '{item.Text}' ";
                    }
                }
                strSql += ")";
            }
            if (this.DropUser_ReceiveID.SelectedItemArray.Count() > 1 || (this.DropUser_ReceiveID.SelectedValue != BLL.Const._Null && this.DropUser_ReceiveID.SelectedItemArray.Count() == 1))
            {//跟踪人
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in this.DropUser_ReceiveID.SelectedItemArray)
                {
                    if (!string.IsNullOrEmpty(item.Text) && item.Text != BLL.Const._Null)
                    {
                        strSql += $" OR User_ReceiveID LIKE '%{item.Text}%' ";
                    }
                }
                strSql += ")";
            }
            if (this.DropUser_Acceptance.SelectedItemArray.Count() > 1 || (this.DropUser_Acceptance.SelectedValue != BLL.Const._Null && this.DropUser_Acceptance.SelectedItemArray.Count() == 1))
            {//责任人
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in this.DropUser_Acceptance.SelectedItemArray)
                {
                    if (!string.IsNullOrEmpty(item.Text) && item.Text != BLL.Const._Null)
                    {
                        strSql += $" OR user_Acceptance = '{item.Text}' ";
                    }
                }
                strSql += ")";
            }
            if (this.DropUnitId.SelectedItemArray.Count() > 1 || (this.DropUnitId.SelectedValue != BLL.Const._Null && this.DropUnitId.SelectedItemArray.Count() == 1))
            {//责任单位
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in this.DropUnitId.SelectedItemArray)
                {
                    if (!string.IsNullOrEmpty(item.Text) && item.Text != BLL.Const._Null)
                    {
                        strSql += $" OR unitname LIKE '%{item.Text}%' ";
                    }
                }
                strSql += ")";
            }
            if (this.DropCNProfessional_ID.SelectedItemArray.Count() > 1 || (this.DropCNProfessional_ID.SelectedValue != BLL.Const._Null && this.DropCNProfessional_ID.SelectedItemArray.Count() == 1))
            {
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in this.DropCNProfessional_ID.SelectedValueArray)
                {
                    if (!string.IsNullOrEmpty(item) && item != BLL.Const._Null)
                    {
                        strSql += $" OR CNProfessionalId LIKE '%{item}%' ";
                    }
                }
                strSql += ")";
            }
            if (this.DropQuestionTypeID.SelectedItemArray.Count() > 1 || (this.DropQuestionTypeID.SelectedValue != BLL.Const._Null && this.DropQuestionTypeID.SelectedItemArray.Count() == 1))
            {//紧急程度
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in this.DropQuestionTypeID.SelectedItemArray)
                {
                    if (!string.IsNullOrEmpty(item.Text) && item.Text != BLL.Const._Null)
                    {
                        strSql += $" OR QuestionTypeName LIKE '%{item.Text}%' ";
                    }
                }
                strSql += ")";
            }
            if (this.DropGJSXTypeID.SelectedItemArray.Count() > 1 || (this.DropGJSXTypeID.SelectedValue != BLL.Const._Null && this.DropGJSXTypeID.SelectedItemArray.Count() == 1))
            {//事项类别
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in this.DropGJSXTypeID.SelectedItemArray)
                {
                    if (!string.IsNullOrEmpty(item.Text) && item.Text != BLL.Const._Null)
                    {
                        strSql += $" OR GJSXTypeName LIKE '%{item.Text}%' ";
                    }
                }
                strSql += ")";
            }
            if (!string.IsNullOrEmpty(this.txtStartTime.Text))//要求完成时间  start
            {
                strSql += " AND CompleteDate > convert(datetime," + "'" + this.txtStartTime.Text.Trim() + "')";
            }
            if (!string.IsNullOrEmpty(this.txtEndTime.Text))//要求完成时间  end
            {
                strSql += " AND CompleteDate 
        /// 查询
        /// 
        /// 
        /// 
        protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            this.BindGrid();
        }
        #endregion 
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.PersonSetMenuId);
            if (buttonList.Count() > 0)
            {
                //if (buttonList.Contains(BLL.Const.BtnAdd))
                //{
                //    this.btnNew.Hidden = false;
                //    //  this.btnImport.Hidden = false;
                //}
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnMenuEdit.Hidden = false;
                }
            }
        }
        #endregion
        #region  删除数据
        /// 
        /// 右键删除事件
        /// 
        /// 
        /// 
        protected void btnMenuDelete_Click(object sender, EventArgs e)
        {
            this.DeleteData();
        }
        /// 
        /// 删除方法
        /// 
        private void DeleteData()
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                string strShowNotify = string.Empty;
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    var user = BLL.UserService.GetUserByUserId(rowID);
                    if (user != null)
                    {
                        string cont = judgementDelete(rowID);
                        if (string.IsNullOrEmpty(cont))
                        {
                            BLL.LogService.AddSys_Log(this.CurrUser, user.UserCode, user.UserId, BLL.Const.PersonSetMenuId, BLL.Const.BtnAdd);
                            BLL.UserService.DeleteUser(rowID);
                        }
                        else
                        {
                            strShowNotify += "人员:" + user.UserName + cont;
                        }
                    }
                }
                BindGrid();
                if (!string.IsNullOrEmpty(strShowNotify))
                {
                    Alert.ShowInTop(strShowNotify, MessageBoxIcon.Warning);
                }
                else
                {
                    ShowNotify("删除数据成功!", MessageBoxIcon.Success);
                }
            }
        }
        #endregion
        #region 分页
        /// 
        /// 分页
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            BindGrid();
        }
        /// 
        /// 分页显示条数下拉框
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, FineUIPro.GridSortEventArgs e)
        {
            BindGrid();
        }
        #endregion
        /// 
        /// Grid行双击事件
        /// 
        /// 
        /// 
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            this.EditData();
        }
        /// 
        /// 右键编辑事件
        /// 
        /// 
        /// 
        protected void btnMenuEdit_Click(object sender, EventArgs e)
        {
            this.EditData();
        }
        /// 
        /// 编辑数据方法
        /// 
        private void EditData()
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInParent("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string Id = Grid1.SelectedRowID;
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("GJSXListEdit.aspx?EditType=Edit&Id={0}", Id, "编辑 - ")));
        }
        #region 判断是否可删除
        /// 
        /// 判断是否可以删除
        /// 
        /// 
        private string judgementDelete(string id)
        {
            string content = string.Empty;
            if (Funs.DB.Project_ProjectUser.FirstOrDefault(x => x.UserId == id) != null)
            {
                content += "已在【项目员工】中使用,不能删除!";
            }
            return content;
        }
        #endregion
        /// 
        /// 参与项目情况
        /// 
        /// 
        /// 
        protected void lbtnPro_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("ParticipateProject.aspx?userId={0}", Grid1.SelectedRowID, "参与项目情况 - "), "参与项目", 1000, 520));
        }
        #region 导入
        /// 
        /// 导入按钮
        /// 
        /// 
        /// 
        protected void btnImport_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("PersonIn.aspx", "导入 - ")));
        }
        #endregion
        /// 
        /// 关闭导入弹出窗口
        /// 
        /// 
        /// 
        protected void Window2_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid();
        }
        protected void ckbAll_CheckedChanged(object sender, CheckedEventArgs e)
        {
            BindGrid();
        }
        #region 导出按钮
        /// 导出按钮
        /// 
        /// 
        ///  
        protected void btnOut_Click(object sender, EventArgs e)
        {
            if (Grid1.Rows.Count == 0)
            {
                ShowNotify("无数据可导出!", MessageBoxIcon.Warning);
                return;
            }
            string rootPath = Server.MapPath("~/");
            string initTemplatePath = string.Empty;
            string uploadfilepath = string.Empty;
            string newUrl = string.Empty;
            string filePath = string.Empty;
            initTemplatePath = Const.GJSXOutTemplateUrl;
            uploadfilepath = rootPath + initTemplatePath;
            newUrl = uploadfilepath.Replace(".xlsx", "(" + DateTime.Now.ToString("yyyyMMddHHmmss") + ").xlsx");
            File.Copy(uploadfilepath, newUrl);
            // 第一步:读取文件流
            NPOI.SS.UserModel.IWorkbook workbook;
            using (FileStream stream = new FileStream(newUrl, FileMode.Open, FileAccess.Read))
            {
                workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(stream);
            }
            Model.SGGLDB db = Funs.DB;
            DataTable tb = BindData();
            // 创建单元格样式
            NPOI.SS.UserModel.ICellStyle cellStyle = workbook.CreateCellStyle();
            cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
            cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
            cellStyle.WrapText = true;
            var font = workbook.CreateFont();
            font.FontHeightInPoints = 10;
            //font.FontHeightInPoints = (short)8.5;字号为小数时要转为short
            cellStyle.SetFont(font);
            // 第二步:创建新数据行
            NPOI.SS.UserModel.ISheet sheet = workbook.GetSheetAt(0);
            NPOI.SS.UserModel.IRow row = null;
            NPOI.SS.UserModel.ICell cell;
            int i = 2;
            for (int j = 0; j < tb.Rows.Count; j++)
            {
                string state = tb.Rows[j]["State"].ToString().Trim();
                string createDate = string.Empty;
                if (tb.Rows[j]["CreateDate"] != DBNull.Value)
                {
                    createDate = string.Format("{0:yyyy-MM-dd}", Convert.ToDateTime(tb.Rows[j]["CreateDate"].ToString()));
                }
                string completeDate = string.Empty;
                if (tb.Rows[j]["CompleteDate"] != DBNull.Value)
                {
                    completeDate = string.Format("{0:yyyy-MM-dd}", Convert.ToDateTime(tb.Rows[j]["CompleteDate"].ToString()));
                }
                string closeDate = string.Empty;
                if (tb.Rows[j]["CloseDate"] != DBNull.Value)
                {
                    closeDate = string.Format("{0:yyyy-MM-dd}", Convert.ToDateTime(tb.Rows[j]["CloseDate"].ToString()));
                }
                // 第二步:创建新数据行
                row = sheet.CreateRow(i);
                // 添加数据
                cell = row.CreateCell(0);
                cell.CellStyle = cellStyle;
                cell.SetCellValue((i - 1).ToString());
                cell = row.CreateCell(1);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(tb.Rows[j]["GJSXID"].ToString());
                cell = row.CreateCell(2);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(tb.Rows[j]["QuestionTypeName"].ToString());
                cell = row.CreateCell(3);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(tb.Rows[j]["CNProfessionalID"].ToString());
                cell = row.CreateCell(4);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(tb.Rows[j]["Detail"].ToString());
                cell = row.CreateCell(5);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(tb.Rows[j]["GJSXTypeName"].ToString());
                cell = row.CreateCell(6);
                NPOI.SS.UserModel.ICellStyle stateCellStyle = workbook.CreateCellStyle();
                stateCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                stateCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                stateCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                stateCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                stateCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                stateCellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
                stateCellStyle.WrapText = true;
                stateCellStyle.SetFont(font);
                if (state == "0")
                {
                    stateCellStyle.FillForegroundColor = IndexedColors.Green.Index;
                    stateCellStyle.FillPattern = FillPattern.SolidForeground;	// 填充方式
                }
                else if (state == "2" || state == "3")
                {
                    stateCellStyle.FillForegroundColor = IndexedColors.SkyBlue.Index;
                    stateCellStyle.FillPattern = FillPattern.SolidForeground;	// 填充方式
                }
                else if (state == "4")
                {
                    stateCellStyle.FillForegroundColor = IndexedColors.Red.Index;
                    stateCellStyle.FillPattern = FillPattern.SolidForeground;	// 填充方式
                }
                cell.CellStyle = stateCellStyle;
                cell.SetCellValue(tb.Rows[j]["StateStr"].ToString());
                cell = row.CreateCell(7);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(createDate);
                cell = row.CreateCell(8);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(completeDate);
                cell = row.CreateCell(9);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(closeDate);
                cell = row.CreateCell(10);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(tb.Rows[j]["unitname"].ToString());
                cell = row.CreateCell(11);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(tb.Rows[j]["username"].ToString());
                cell = row.CreateCell(12);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(tb.Rows[j]["User_Acceptance"].ToString());
                cell = row.CreateCell(13);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(tb.Rows[j]["User_ReceiveID"].ToString());
                //cell = row.CreateCell(14);
                //cell.CellStyle = cellStyle;
                //cell.SetCellValue("");
                i++;
            }
            // 第三步:写入文件流
            using (FileStream stream = new FileStream(newUrl, FileMode.Create, FileAccess.Write))
            {
                workbook.Write(stream);
                workbook.Close();
            }
            string fileName = Path.GetFileName(newUrl);
            FileInfo info = new FileInfo(newUrl);
            long fileSize = info.Length;
            Response.Clear();
            Response.ContentType = "application/x-zip-compressed";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.AddHeader("Content-Length", fileSize.ToString());
            Response.TransmitFile(newUrl, 0, fileSize);
            Response.Flush();
            Response.Close();
            File.Delete(newUrl);
        }
        #endregion
    }
}