using BLL;
using BLL.Common;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using AspNet = System.Web.UI.WebControls;
using FineUIPro.Web.common;

namespace FineUIPro.Web.SES
{
    public partial class CSafePunish : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetButtonPower();//权限设置

                btnNew.OnClientClick = Window1.GetShowReference("CSafePunishEdit.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());

                var pun = from x in Funs.DB.View_EMC_Punishment
                          where x.Flag == "1" && x.Contract_AdminId != null
                          orderby x.Contract_Admin
                          select new { x.Contract_AdminId, x.Contract_Admin };
                drpContractAdmin.DataValueField = "Contract_AdminId";
                drpContractAdmin.DataTextField = "Contract_Admin";
                drpContractAdmin.DataSource = pun.Distinct();
                drpContractAdmin.DataBind();
                Funs.FineUIPleaseSelect(drpContractAdmin);

                ddlPageSize.SelectedValue = Grid1.PageSize.ToString();
                // 绑定表格
                BindGrid();
            }
        }

        private void BindGrid()
        {
            string strSql = @"SELECT * FROM dbo.View_EMC_Punishment WHERE Flag='1'  ";

            List<SqlParameter> listStr = new List<SqlParameter>();
            if (!string.IsNullOrEmpty(this.txtFO_NO.Text.Trim()))
            {
                strSql += " AND FO_NO LIKE @FO_NO";
                listStr.Add(new SqlParameter("@FO_NO", "%" + this.txtFO_NO.Text.Trim() + "%"));
            }
            if (drpContractAdmin.SelectedValue != Const._Null && (drpContractAdmin.SelectedValue != null))
            {
                strSql += " AND Contract_AdminId = @Contract_AdminId";
                listStr.Add(new SqlParameter("@Contract_AdminId", drpContractAdmin.SelectedValue));
            }
            if (!string.IsNullOrEmpty(txtPunishDate.Text))
            {
                DateTime startDate = Convert.ToDateTime(txtPunishDate.Text + "-01");
                DateTime endDate = startDate.AddMonths(1);
                strSql += " AND PunishDate >= @StartDate";
                listStr.Add(new SqlParameter("@StartDate", startDate));

                strSql += " AND PunishDate < @EndDate";
                listStr.Add(new SqlParameter("@EndDate", endDate));
            }

            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);

            Grid1.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }

        #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("CSafePunishEdit.aspx?punishmentId={0}", Id, "编辑 - ")));

        }

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

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

        #region  删除数据
        /// <summary>
        /// 批量删除数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            this.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();
                    var pun = BLL.PunishmentService.GetPunishmentById(rowID);
                    if (pun != null)
                    {
                        if (judgementDelete(rowID, false))
                        {
                            BLL.PunishmentService.DeletePunishmentById(rowID);
                        }
                    }
                }
                BindGrid();
                BLL.Sys_LogService.AddLog(this.CurrUser.UserId, "Delete Contractor Safety Punishment");
                ShowNotify("Deleted successfully!");
            }
        }
        #endregion

        #region 查询
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion

        #region 邮件发送
        protected void btnEmail_Click(object sender, EventArgs e)
        {
            List<Model.View_EMC_Punishment> pList = (from x in Funs.DB.View_EMC_Punishment
                                                     where x.Flag == "1" && x.EmailIsSend == "否" 
                                                            && (x.PunishDate.Value.Year + x.PunishDate.Value.Month) == (DateTime.Now.Year + DateTime.Now.Month)
                                                     select x).ToList();
            if (pList.Count()>0)
            {
                Model.EmailPop pops = Funs.DB.EmailPop.FirstOrDefault(x => x.EmailID == BLL.Const.EmailPopId);
                if (pops == null)
                {
                    return;
                }
                string[] mailTo = null;
                string mailBody = string.Empty;
                string mailAttch = string.Empty;
                string mailCode = string.Empty;
                string mailPriority = string.Empty;
                string[] mailCC = null;
                string resultMessage = "";
                bool result = false;

                //List<Model.Sys_User> userCCList = new List<Model.Sys_User>();

                //// 合同员是否该合同的合同员,角色是否都有
                //var userToList = from x in Funs.DB.Sys_User
                //                 join y in Funs.DB.Sys_Role on x.RoleId equals y.RoleId
                //                 where (y.RoleName == "Purchasing Manager" || y.RoleName == "Buy_Manager" || y.RoleName == "Contract Administrator"
                //                        || y.RoleName == "Project_Admin" || y.RoleName == "Contractor_Leader" || y.RoleName == "CTS_CManagement"
                //                        ) && x.Email != null && x.Email != ""
                //                 select x;

                //var userCC = from x in Funs.DB.Sys_User
                //             join y in Funs.DB.Sys_Role on x.RoleId equals y.RoleId
                //             where (y.RoleName == "CTS/C" || y.RoleName == "CTS_Training" || y.RoleName == "CTS/S_Manager"
                //                    || y.RoleName == "CTS/S_Engineer" || y.RoleName == "CTM/T" || y.RoleName == "CTE/D Manager"
                //                    ) && x.Email != null && x.Email != ""
                //             select x;
                //userCCList.AddRange(userCC);
                //// 获取CTE部门Department leader
                //var depList = from x in Funs.DB.Base_Depart where x.DepartCode.Contains("CTE") && x.DepartLeader != null && x.DepartLeader != "" select x;
                //if (depList.Count() > 0)
                //{
                //    var leaderList = depList.Select(x => x.DepartLeader).Distinct().ToArray();
                //    var userCCLeader = from x in Funs.DB.Sys_User where leaderList.Contains(x.UserId) select x;
                //    userCCList.AddRange(userCCLeader);
                //}

                //mailTo = userToList.Select(x => x.Email).Distinct().ToArray();
                //mailCC = userCCList.Select(x => x.Email).Distinct().ToArray();

                mailCode = DateTime.Now.ToString();

                var emailTemplate = Funs.DB.SendEmailTemplate.Where(x => x.EmailName.Contains("违规扣款通知"));
                if (emailTemplate.Count() > 0)
                {
                    var Sendeplist = BLL.SendEmail.SendEmailTemplateService.GetSenderTopeopleList(emailTemplate.First().EmailId,"0");
                    //var Sendres = from m in Sendeplist
                    //              join k in Sys_UserService.GetUserList() on m.EmuserID equals k.UserId
                    //              select new { EmuaerEmailAddress = k.Email, senduserid = k.UserId };

                    var CCeplist = BLL.SendEmail.SendEmailTemplateService.GetSenderTopeopleList(emailTemplate.First().EmailId, "1");
                    //var CCres = from m in CCeplist
                    //            join k in Sys_UserService.GetUserList() on m.EmuserID equals k.UserId
                    //            select new { EmuaerEmailAddress = k.Email, senduserid = k.UserId };

                    mailTo = Sendeplist.Where(o => o.EmuaerEmailAddress != null).Select(o => o.EmuaerEmailAddress).ToList().ToArray();
                    mailCC = CCeplist.Where(o => o.EmuaerEmailAddress != null).Select(o => o.EmuaerEmailAddress).ToList().ToArray();


                    string templetpath = emailTemplate.Select(x => x.EmailContext).FirstOrDefault();
                    NameValueCollection myCol = new NameValueCollection();
                    NameValueCollection myCol1 = new NameValueCollection();
                    mailBody = TemplateHelper.BulidByFile2(templetpath, myCol);
                    string EmailName = emailTemplate.Select(x => x.EmailName).FirstOrDefault();
                    string mailSubject = TemplateHelper.BulidByFile2(EmailName, myCol1);
                    result = MailHelper.SendPunishMail(pops, pops.EmailYx, mailTo, mailSubject, mailBody, mailAttch, mailCode, mailPriority, mailCC, pList, out resultMessage);

                    // 发送成功后写入表中
                    if (result == true)
                    {
                        foreach (var p in pList)
                        {
                            var punish = BLL.PunishmentService.GetPunishmentById(p.PunishmentId);
                            punish.EmailIsSend = true;
                            Funs.DB.SubmitChanges();
                        }
                       
                        ShowNotify("Email sent successfully!", MessageBoxIcon.Success);
                    }
                    else
                    {
                        Alert.ShowInTop("Email sending failed!", MessageBoxIcon.Warning);
                        return;
                    }
                }
            }
            else
            {
                Alert.ShowInTop("No eligible emails need to be send!", MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion

        #region 查看
        protected void btnMenuView_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("CSafePunishEdit.aspx?punishmentId={0}&view=1", Id, "查看 - ")));
        }
        #endregion

        #region 判断是否可删除
        /// <summary>
        /// 判断是否可以删除
        /// </summary>
        /// <returns></returns>
        private bool judgementDelete(string id, bool isShow)
        {
            string content = string.Empty;
            //if (Funs.DB.Sys_User.FirstOrDefault(x => x.RoleId == id) != null)
            //{
            //    content = "This role is already in use in [user information] and cannot be deleted!";
            //}

            if (string.IsNullOrEmpty(content))
            {
                return true;
            }
            else
            {
                if (isShow)
                {
                    Alert.ShowInTop(content);
                }
                return false;
            }
        }
        #endregion

        #region 关闭弹出窗口
        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Window1_Close(object sender, EventArgs e)
        {
            BindGrid();
            drpContractAdmin.Items.Clear();
            var pun = from x in Funs.DB.View_EMC_Punishment
                      where x.Flag == "1" && x.Contract_AdminId != null
                      orderby x.Contract_Admin
                      select new { x.Contract_AdminId, x.Contract_Admin };
            drpContractAdmin.DataValueField = "Contract_AdminId";
            drpContractAdmin.DataTextField = "Contract_Admin";
            drpContractAdmin.DataSource = pun.Distinct();
            drpContractAdmin.DataBind();
            Funs.FineUIPleaseSelect(drpContractAdmin);
        }
        #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 btnExport_Click(object sender, EventArgs e)
        {
            string rootPath = Server.MapPath("~/") + Const.ExcelUrl;
            //模板文件
            string TempletFileName = rootPath + "Punishment.xlsx";
            //导出文件
            string filePath = rootPath + DateTime.Now.ToString("yyyyMMddhhmmss") + "\\";
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            string ReportFileName = filePath + "out.xlsx";

            FileStream file = new FileStream(TempletFileName, FileMode.Open, FileAccess.Read);
            XSSFWorkbook hssfworkbook = new XSSFWorkbook(file);

            #region FC_List
            XSSFSheet reportModel = (XSSFSheet)hssfworkbook.GetSheet("Sheet1");

            IDataFormat dataformat = hssfworkbook.CreateDataFormat();
            ICellStyle styleQfw = hssfworkbook.CreateCellStyle();
            styleQfw.DataFormat = dataformat.GetFormat("#,##0.00");

            ICellStyle styleDate = hssfworkbook.CreateCellStyle();
            styleDate.DataFormat = dataformat.GetFormat("yyyy/m/d");

            ICellStyle styleTime = hssfworkbook.CreateCellStyle();
            styleTime.DataFormat = dataformat.GetFormat("yyyy/m/d HH:mm:ss");

            XSSFFont cs_content_Font = (XSSFFont)hssfworkbook.CreateFont(); //创建字体
            cs_content_Font.FontName = "等线";//字体
            cs_content_Font.FontHeightInPoints = 10; //字体大小

            Grid1.PageSize = 1000000;
            BindGrid();

            if (Grid1.Rows.Count() > 0)
            {
                for (int i = 1; i <= Grid1.Rows.Count(); i++)
                {
                    if (reportModel.GetRow(i) == null) reportModel.CreateRow(i);

                    #region 列赋值
                    //Date
                    if (reportModel.GetRow(i).GetCell(0) == null) reportModel.GetRow(i).CreateCell(0);
                    if (Grid1.Rows[i - 1].Values[1] != null && Grid1.Rows[i - 1].Values[1].ToString() != "")
                    {
                        DateTime date = Convert.ToDateTime(Grid1.Rows[i - 1].Values[1]);
                        reportModel.GetRow(i).GetCell(0).SetCellValue(date.ToString("yyyy/MM/dd")); 
                        reportModel.GetRow(i).GetCell(0).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    }
                   
                    //Time
                    if (reportModel.GetRow(i).GetCell(1) == null) reportModel.GetRow(i).CreateCell(1);
                    reportModel.GetRow(i).GetCell(1).SetCellValue(Grid1.Rows[i - 1].Values[2].ToString());
                    reportModel.GetRow(i).GetCell(1).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // Contract No.
                    if (reportModel.GetRow(i).GetCell(2) == null) reportModel.GetRow(i).CreateCell(2);
                    reportModel.GetRow(i).GetCell(2).SetCellValue(Grid1.Rows[i - 1].Values[3].ToString());
                    reportModel.GetRow(i).GetCell(2).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式

                    // Discipline
                    if (reportModel.GetRow(i).GetCell(3) == null) reportModel.GetRow(i).CreateCell(3);
                    reportModel.GetRow(i).GetCell(3).SetCellValue(Grid1.Rows[i - 1].Values[4].ToString());
                    reportModel.GetRow(i).GetCell(3).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // Contractor
                    if (reportModel.GetRow(i).GetCell(4) == null) reportModel.GetRow(i).CreateCell(4);
                    reportModel.GetRow(i).GetCell(4).SetCellValue(Grid1.Rows[i - 1].Values[5].ToString());
                    reportModel.GetRow(i).GetCell(4).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // Location
                    if (reportModel.GetRow(i).GetCell(5) == null) reportModel.GetRow(i).CreateCell(5);
                    reportModel.GetRow(i).GetCell(5).SetCellValue(Grid1.Rows[i - 1].Values[6].ToString());
                    reportModel.GetRow(i).GetCell(5).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // Violation Description
                    if (reportModel.GetRow(i).GetCell(6) == null) reportModel.GetRow(i).CreateCell(6);
                    reportModel.GetRow(i).GetCell(6).SetCellValue(Grid1.Rows[i - 1].Values[7].ToString());
                    reportModel.GetRow(i).GetCell(6).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // Company(RMB)
                    if (reportModel.GetRow(i).GetCell(7) == null) reportModel.GetRow(i).CreateCell(7);
                    reportModel.GetRow(i).GetCell(7).SetCellValue(Grid1.Rows[i - 1].Values[8].ToString());
                    reportModel.GetRow(i).GetCell(7).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // Individual(RMB)
                    if (reportModel.GetRow(i).GetCell(8) == null) reportModel.GetRow(i).CreateCell(8);
                    reportModel.GetRow(i).GetCell(8).SetCellValue(Grid1.Rows[i - 1].Values[9].ToString());
                    reportModel.GetRow(i).GetCell(8).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // Backcharge(RMB)
                    if (reportModel.GetRow(i).GetCell(9) == null) reportModel.GetRow(i).CreateCell(9);
                    reportModel.GetRow(i).GetCell(9).SetCellValue(Grid1.Rows[i - 1].Values[10].ToString());
                    reportModel.GetRow(i).GetCell(9).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // Violation Degree
                    if (reportModel.GetRow(i).GetCell(10) == null) reportModel.GetRow(i).CreateCell(10);
                    reportModel.GetRow(i).GetCell(10).SetCellValue(Grid1.Rows[i - 1].Values[11].ToString());
                    reportModel.GetRow(i).GetCell(10).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // Contract Admin
                    if (reportModel.GetRow(i).GetCell(11) == null) reportModel.GetRow(i).CreateCell(11);
                    reportModel.GetRow(i).GetCell(11).SetCellValue(Grid1.Rows[i - 1].Values[12].ToString());
                    reportModel.GetRow(i).GetCell(11).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // Main Coordinator
                    if (reportModel.GetRow(i).GetCell(12) == null) reportModel.GetRow(i).CreateCell(12);
                    reportModel.GetRow(i).GetCell(12).SetCellValue(Grid1.Rows[i - 1].Values[13].ToString());
                    reportModel.GetRow(i).GetCell(12).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // M.C.Dept
                    if (reportModel.GetRow(i).GetCell(13) == null) reportModel.GetRow(i).CreateCell(13);
                    reportModel.GetRow(i).GetCell(13).SetCellValue(Grid1.Rows[i - 1].Values[14].ToString());
                    reportModel.GetRow(i).GetCell(13).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // User Representative
                    if (reportModel.GetRow(i).GetCell(14) == null) reportModel.GetRow(i).CreateCell(14);
                    reportModel.GetRow(i).GetCell(14).SetCellValue(Grid1.Rows[i - 1].Values[15].ToString());
                    reportModel.GetRow(i).GetCell(14).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // BYC RU
                    if (reportModel.GetRow(i).GetCell(15) == null) reportModel.GetRow(i).CreateCell(15);
                    reportModel.GetRow(i).GetCell(15).SetCellValue(Grid1.Rows[i - 1].Values[16].ToString());
                    reportModel.GetRow(i).GetCell(15).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式

                    // BYC Resp Manager
                    if (reportModel.GetRow(i).GetCell(16) == null) reportModel.GetRow(i).CreateCell(16);
                    reportModel.GetRow(i).GetCell(16).SetCellValue(Grid1.Rows[i - 1].Values[17].ToString());
                    reportModel.GetRow(i).GetCell(16).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式

                    // Violation Inspector
                    if (reportModel.GetRow(i).GetCell(17) == null) reportModel.GetRow(i).CreateCell(17);
                    reportModel.GetRow(i).GetCell(17).SetCellValue(Grid1.Rows[i - 1].Values[18].ToString());
                    reportModel.GetRow(i).GetCell(17).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // Inspection Department
                    if (reportModel.GetRow(i).GetCell(18) == null) reportModel.GetRow(i).CreateCell(18);
                    reportModel.GetRow(i).GetCell(18).SetCellValue(Grid1.Rows[i - 1].Values[19].ToString());
                    reportModel.GetRow(i).GetCell(18).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // Backcharge SES No.
                    if (reportModel.GetRow(i).GetCell(19) == null) reportModel.GetRow(i).CreateCell(19);
                    reportModel.GetRow(i).GetCell(19).SetCellValue(Grid1.Rows[i - 1].Values[20].ToString());
                    reportModel.GetRow(i).GetCell(19).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                   // Backcharge Completion Date
                    if (reportModel.GetRow(i).GetCell(20) == null) reportModel.GetRow(i).CreateCell(20);
                    if (Grid1.Rows[i - 1].Values[21] != null && Grid1.Rows[i - 1].Values[21].ToString() != "")
                    {
                        DateTime cdate = Convert.ToDateTime(Grid1.Rows[i - 1].Values[21]);
                        reportModel.GetRow(i).GetCell(20).SetCellValue(cdate.ToString("yyyy/MM/dd"));
                        reportModel.GetRow(i).GetCell(20).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    }
                    // Violation Related SES
                    if (reportModel.GetRow(i).GetCell(21) == null) reportModel.GetRow(i).CreateCell(21);
                    reportModel.GetRow(i).GetCell(21).SetCellValue(Grid1.Rows[i - 1].Values[22].ToString());
                    reportModel.GetRow(i).GetCell(21).CellStyle.SetFont(cs_content_Font);//将字体绑定到样式
                    // If send mail
                    if (reportModel.GetRow(i).GetCell(22) == null) reportModel.GetRow(i).CreateCell(22);
                    reportModel.GetRow(i).GetCell(22).SetCellValue(Grid1.Rows[i - 1].Values[23].ToString());
                    reportModel.GetRow(i).GetCell(22).CellStyle.SetFont(cs_content_Font);

                    #endregion
                }
            }
            #endregion
            reportModel.ForceFormulaRecalculation = true;

            using (FileStream filess = File.OpenWrite(ReportFileName))
            {
                hssfworkbook.Write(filess);
            }
            FileInfo filet = new FileInfo(ReportFileName);
            Response.Clear();
            Response.Charset = "GB2312";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            // 添加头信息,为"文件下载/另存为"对话框指定默认文件名
            Response.AddHeader("Content-Disposition", "attachment; filename=CSafe_Punishment_" + Server.UrlEncode(DateTime.Now.ToString("yyyyMMddhhmmss") + ".xlsx"));
            // 添加头信息,指定文件大小,让浏览器能够显示下载进度
            Response.AddHeader("Content-Length", filet.Length.ToString());
            // 指定返回的是一个不能被客户端读取的流,必须被下载
            Response.ContentType = "application/ms-excel";
            // 把文件流发送到客户端
            Response.WriteFile(filet.FullName);
            // 停止页面的执行
            Response.End();

        }
        #endregion

        #region 权限设置
        /// <summary>
        /// 菜单按钮权限
        /// </summary>
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.UserId, BLL.Const.CSafePunishMenuId);
            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;
                }
                //if (buttonList.Contains(BLL.Const.BtnSave))
                //{
                //    this.Grid1.EnableRowDoubleClickEvent = true;
                //}
                if (buttonList.Contains(BLL.Const.BtnSend))
                {
                    this.btnEmail.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnOut))
                {
                    this.btnExport.Hidden = false;
                }
                //else
                //{
                //    this.Grid1.EnableRowDoubleClickEvent = false;
                //}
            }
        }
        #endregion
    }
}