using System;
using System.Collections.Generic;
using AspNet = System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System.Linq;
using System.IO;
using BLL;
using System.Text;
namespace FineUIPro.Web.WeldingProcess.TrustManage
{
    public partial class TrustBatchSelect : PageBase
    {
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.ddlPageSize.SelectedValue = this.Grid1.PageSize.ToString();
                BLL.Project_InstallationService.InitInstallationDropDownList(this.drpInstallation, true, this.CurrUser.LoginProjectId, Resources.Lan.PleaseSelect);
            }
        }
        /// 
        /// 绑定数据
        /// 
        private void BindGrid()
        {
            string strSql = @"SELECT * FROM dbo.View_Batch_BatchTrustItemSelect 
                                WHERE ProjectId=@ProjectId ";
            List listStr = new List();
            listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            if (drpInstallation.SelectedValue != Const._Null)
            {
                strSql += " AND InstallationId = @InstallationId";
                listStr.Add(new SqlParameter("@InstallationId", drpInstallation.SelectedValue));
            }
            if (!string.IsNullOrEmpty(this.txtTrustBatchCode.Text))
            {
                strSql += " AND TrustBatchCode LIKE @TrustBatchCode";
                listStr.Add(new SqlParameter("@TrustBatchCode", "%" + this.txtTrustBatchCode.Text.Trim() + "%"));
            }
            if (!string.IsNullOrEmpty(this.txtTrustDate.Text))
            {
                strSql += " AND TrustDate = @TrustDate";
                listStr.Add(new SqlParameter("@TrustDate", this.txtTrustDate.Text));
            }
            if (!string.IsNullOrEmpty(txtPipeLineCode.Text))
            {
                strSql += " AND PipelineCode LIKE @PipelineCode";
                listStr.Add(new SqlParameter("@PipelineCode", "%" + this.txtPipeLineCode.Text.Trim() + "%"));
            }
            if (!string.IsNullOrEmpty(this.txtWeldJointCode.Text))
            {
                strSql += " AND WeldJointCode = @WeldJointCode";
                listStr.Add(new SqlParameter("@WeldJointCode", this.txtWeldJointCode.Text));
            }
            if (!string.IsNullOrEmpty(this.txtWelderCode.Text))
            {
                strSql += " AND WelderCode LIKE @WelderCode";
                listStr.Add(new SqlParameter("@WelderCode", "%" + this.txtWelderCode.Text.Trim() + "%"));
            }
            if (this.ckbFirstTwo.Checked)
            {
                strSql += " AND IsWelderFirst = @IsWelderFirst";
                listStr.Add(new SqlParameter("@IsWelderFirst", "是"));
            }
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            this.Grid1.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        /// 
        /// 改变索引事件
        /// 
        /// 
        /// 
        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)
        {
            this.BindGrid();
        }
        #endregion
        #region 统计按钮事件
        /// 
        /// 统计
        /// 
        /// 
        /// 
        protected void BtnAnalyse_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 导出按钮
        /// 导出按钮
        /// 
        /// 
        /// 
        protected void btnOut_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            string filename = Funs.GetNewFileName();
            Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(Resources.Lan.RequestSheetNumber + filename, System.Text.Encoding.UTF8) + ".xls");
            Response.ContentType = "application/excel";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.Write(GetGridTableHtml(Grid1));
            Response.End();
        }
        /// 
        /// 导出方法
        /// 
        /// 
        /// 
        private string GetGridTableHtml(Grid grid)
        {
            StringBuilder sb = new StringBuilder();
            grid.PageSize = 1000000;
            BindGrid();
            sb.Append("");
            sb.Append("");
            sb.Append("");
            foreach (GridColumn column in grid.Columns)
            {
                sb.AppendFormat("| {0} | ", column.HeaderText);
            }
            sb.Append("
");
            foreach (GridRow row in grid.Rows)
            {
                sb.Append("");
                foreach (GridColumn column in grid.Columns)
                {
                    string jot = row.Values[column.ColumnIndex].ToString();
                    string html = string.Empty;
                    if (column.ColumnID == "WeldJointCode" && jot.Split('-').Length > 1)
                    {
                        html = "'" + row.Values[column.ColumnIndex].ToString();
                    }
                    else
                    {
                        html = row.Values[column.ColumnIndex].ToString();
                    }
                     
                    if (column.ColumnID == "tfNumber")
                    {
                        html = (row.FindControl("labNumber") as AspNet.Label).Text;
                    }
                    sb.AppendFormat("| {0} | ", html);
                }
                sb.Append("
");
            }
            sb.Append("
");
            return sb.ToString();
        }
        #endregion
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (drpInstallation.SelectedValue == Const._Null)
            {
                Alert.ShowInParent("请选择装置!");
                return;
            }
            if (string.IsNullOrEmpty(txtTrustDate.Text))
            {
                Alert.ShowInParent("请选择导出的委托日期!");
                return;
            }
            string rootPath = Server.MapPath("~/") + Const.ExcelUrl;
            //模板文件
            string TempletFileName = rootPath + "DailyTrust.xlsx";
            //导出文件
            string filePath = rootPath + DateTime.Now.ToString("yyyyMMddhhmmss") + "\\";
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            string ReportFileName = filePath + "out.xls";
            FileStream file = new FileStream(TempletFileName, FileMode.Open, FileAccess.Read);
            XSSFWorkbook hssfworkbook = new XSSFWorkbook(file);
            XSSFSheet ws = (XSSFSheet)hssfworkbook.GetSheetAt(0);
            var project = BLL.Base_ProjectService.GetProjectByProjectId(this.CurrUser.LoginProjectId);
            if (ws.GetRow(0).GetCell(6) == null) ws.GetRow(0).CreateCell(6);
            ws.GetRow(0).GetCell(6).SetCellValue("工程名称:" + project.ProjectName);
            if (ws.GetRow(1).GetCell(2) == null) ws.GetRow(1).CreateCell(2);
            ws.GetRow(1).GetCell(2).SetCellValue("日期:"+txtTrustDate.Text);
            if (ws.GetRow(1).GetCell(6) == null) ws.GetRow(1).CreateCell(6);
            ws.GetRow(1).GetCell(6).SetCellValue("单元名称:" + drpInstallation.SelectedText);
            //获取委托单信息
            var trustList = Funs.DB.View_Batch_BatchTrustItem.Where(p => p.ProjectId == CurrUser.LoginProjectId && p.InstallationId == drpInstallation.SelectedValue && p.TrustDate == txtTrustDate.Text).ToList();
            if (trustList.Count() > 0)
            {
                int rowindex = 3;
                foreach (var item in trustList)
                {
                    if (ws.GetRow(rowindex) == null) ws.CreateRow(rowindex);
                    if (ws.GetRow(rowindex).GetCell(0) == null) ws.GetRow(rowindex).CreateCell(0);
                    ws.GetRow(rowindex).GetCell(0).SetCellValue(rowindex-2);
                    if (ws.GetRow(rowindex).GetCell(1) == null) ws.GetRow(rowindex).CreateCell(1);
                    ws.GetRow(rowindex).GetCell(1).SetCellValue(item.PipelineCode);
                    if (ws.GetRow(rowindex).GetCell(2) == null) ws.GetRow(rowindex).CreateCell(2);
                    ws.GetRow(rowindex).GetCell(2).SetCellValue(item.WeldJointCode);
                    if (ws.GetRow(rowindex).GetCell(3) == null) ws.GetRow(rowindex).CreateCell(3);
                    ws.GetRow(rowindex).GetCell(3).SetCellValue(item.WelderCode);
                    if (ws.GetRow(rowindex).GetCell(4) == null) ws.GetRow(rowindex).CreateCell(4);
                    ws.GetRow(rowindex).GetCell(4).SetCellValue(item.Specification);
                    if (ws.GetRow(rowindex).GetCell(5) == null) ws.GetRow(rowindex).CreateCell(5);
                    ws.GetRow(rowindex).GetCell(5).SetCellValue(item.MaterialCode);
                    if (ws.GetRow(rowindex).GetCell(6) == null) ws.GetRow(rowindex).CreateCell(6);
                    ws.GetRow(rowindex).GetCell(6).SetCellValue(item.DetectionRateCode);
                    if (ws.GetRow(rowindex).GetCell(7) == null) ws.GetRow(rowindex).CreateCell(7);
                    ws.GetRow(rowindex).GetCell(7).SetCellValue(item.TrustBatchCode);
                    if (ws.GetRow(rowindex).GetCell(8) == null) ws.GetRow(rowindex).CreateCell(8);
                    ws.GetRow(rowindex).GetCell(8).SetCellValue(item.Remark);
                    rowindex++;
                }
            }
            ws.ForceFormulaRecalculation = true;
            using (FileStream filess = System.IO.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=日管道焊口检测委托单(" + txtTrustDate.Text + ").xlsx");
            // 添加头信息,指定文件大小,让浏览器能够显示下载进度
            Response.AddHeader("Content-Length", filet.Length.ToString());
            // 指定返回的是一个不能被客户端读取的流,必须被下载
            Response.ContentType = "application/ms-excel";
            // 把文件流发送到客户端
            Response.WriteFile(filet.FullName);
            // 停止页面的执行
            Response.End();
        }
    }
}