using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.UI;
using BLL;
using AspNet = System.Web.UI.WebControls;
using Model;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace FineUIPro.Web.WeldingProcess.TrustManage
{
    public partial class TrustBatchIn : PageBase
    {
        #region 定义变量
        /// 
        /// 上传预设的虚拟路径
        /// 
        private string initPath = Const.ExcelUrl;
        /// 
        /// 错误集合
        /// 
        public static string errorInfos = string.Empty;
        public string BatchCode
        {
            get
            {
                return (string)ViewState["BatchCode"];
            }
            set
            {
                ViewState["BatchCode"] = value;
            }
        }
        #endregion
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.hdFileName.Text = string.Empty;
                this.hdCheckResult.Text = string.Empty;
                errorInfos = string.Empty;
            }
        }
        #endregion
        #region 审核
        /// 
        /// 审核
        /// 
        /// 
        /// 
        protected void btnAudit_Click(object sender, EventArgs e)
        {
            errorInfos = string.Empty;
            if (this.fuAttachUrl.HasFile == false)
            {
                ShowNotify("请选择Excel文件!", MessageBoxIcon.Warning);
                return;
            }
            string IsXls = Path.GetExtension(this.fuAttachUrl.FileName).ToString().Trim().ToLower();
            if (IsXls != ".xls" && IsXls != ".xlsx")
            {
                ShowNotify("只能选择Excel文件!", MessageBoxIcon.Warning);
                return;
            }
            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;
            }
            if (ds.Tables.Count > 0)
            {
                List trustList = new List();
                var units = from x in Funs.DB.Base_Unit select x;
                var area = from x in Funs.DB.Project_WorkArea where x.ProjectId == this.CurrUser.LoginProjectId select x;
                var installation = from x in Funs.DB.Project_Installation where x.ProjectId == this.CurrUser.LoginProjectId select x;
                var trustIn = from x in Funs.DB.View_TrustBathcIn where x.ProjectId == this.CurrUser.LoginProjectId select x;
                var pipeList = from x in Funs.DB.Pipeline_Pipeline where x.ProjectId == this.CurrUser.LoginProjectId select x;
                List logListData = new List();
                string BatchNo = DateTime.Now.ToString("yyyyMMddHHmmss");
                BatchCode = BatchNo;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string result = string.Empty;
                    var log = new Model.TrustBatchImportErrorLog();
                    string col0 = ds.Tables[0].Rows[i][0].ToString().Trim();
                    string col1 = ds.Tables[0].Rows[i][1].ToString().Trim();
                    string col2 = ds.Tables[0].Rows[i][2].ToString().Trim();
                    string col3 = ds.Tables[0].Rows[i][3].ToString().Trim();
                    string col4 = ds.Tables[0].Rows[i][4].ToString().Trim();
                    string col5 = ds.Tables[0].Rows[i][5].ToString().Trim();
                    string col6 = ds.Tables[0].Rows[i][6].ToString().Trim();
                    string col7 = ds.Tables[0].Rows[i][7].ToString().Trim();
                    string col8 = ds.Tables[0].Rows[i][8].ToString().Trim();
                    string col9 = ds.Tables[0].Rows[i][9].ToString().Trim();
                    log.Id = SQLHelper.GetNewID(typeof(TrustBatchImportErrorLog));
                    log.RowID = (i + 2);
                    log.BatchNo = BatchNo;
                    log.TrustBatchCode = col0;
                    log.InstallCode = col1;
                    log.AreaCode = col2;
                    log.PipelineCode = col3;
                    log.WeldJointCode = col4;
                    log.DetectionType = col5;
                    log.TrustDate = col6;
                    log.UnitCode = col7;
                    log.SurfaceState = col8;
                    log.Opportunity = col9;
                    log.CreatedTime = DateTime.Now;
                    Model.Batch_BatchTrust t = new Model.Batch_BatchTrust();
                    if (string.IsNullOrEmpty(col0))
                    {
                        result += "委托单号此项为必填项!" + "|";
                    }
                    else
                    {
                        var oldTrust = Funs.DB.Batch_BatchTrust.FirstOrDefault(x => x.TrustBatchCode == col0);
                        if (oldTrust != null)
                        {
                            result += "委托单号 [" + col0 + "]已存在!" + "|";
                        }
                        else
                        {
                            t.TrustBatchCode = col0;
                        }
                    }
                    string installationId = string.Empty;
                    if (!string.IsNullOrEmpty(col1))
                    {
                        Model.Project_Installation ins = installation.FirstOrDefault(x => x.InstallationCode == col1);
                        if (ins == null)
                        {
                            result += "装置编号 [" + col1 + "]不存在!" + "|";
                        }
                        else
                        {
                            installationId = ins.InstallationId;
                            t.InstallationId = installationId;
                        }
                    }
                    else
                    {
                        result += "装置编号此项为必填项!" + "|";
                    }
                    string workAreaId = string.Empty;
                    if (!string.IsNullOrEmpty(col2))
                    {
                        Model.Project_WorkArea workArea = area.FirstOrDefault(x => x.WorkAreaCode == col2 && x.InstallationId == installationId);
                        if (workArea == null)
                        {
                            result += "区域编号 [" + col2 + "]不存在!" + "|";
                        }
                        else
                        {
                            workAreaId = workArea.WorkAreaId;
                            t.WorkAreaId = workAreaId;
                        }
                    }
                    else
                    {
                        result += "区域编号此项为必填项!" + "|";
                    }
                    string pipelineId = string.Empty;
                    if (!string.IsNullOrEmpty(col3))
                    {
                        var pipe = pipeList.FirstOrDefault(x => x.PipelineCode == col3 && x.WorkAreaId == workAreaId);
                        if (pipe == null)
                        {
                            result += "该区域管线号 [" + col3 + "]不存在!" + "|";
                        }
                        else
                        {
                            pipelineId = pipe.PipelineId;
                            t.PipelineId = pipelineId;
                        }
                    }
                    else
                    {
                        result += "管线号此项为必填项!" + "|";
                    }
                    string weldJointId = string.Empty;
                    if (!string.IsNullOrEmpty(col4))
                    {
                        var weldJoint = from x in Funs.DB.Pipeline_WeldJoint where x.PipelineId == pipelineId && x.WeldJointCode == col4 select x;
                        if (weldJoint.Count() == 0)
                        {
                            result += "焊口号 [" + col4 + "]不存在!" + "|";
                        }
                        else if (weldJoint.Count() == 1)
                        {
                            weldJointId = weldJoint.First().WeldJointId;
                            t.WeldingMethodId = weldJoint.First().WeldingMethodId;
                            t.GrooveTypeId = weldJoint.First().GrooveTypeId;
                        }
                        else
                        {
                            result += "焊口号 [" + col4 + "]重复!" + "|";
                        }
                    }
                    else
                    {
                        result += "焊口号此项为必填项!" + "|";
                    }
                    string ndeId = string.Empty;
                    if (!string.IsNullOrEmpty(col5))
                    {
                        var nde = Funs.DB.Base_DetectionType.FirstOrDefault(x => x.DetectionTypeCode == col5);
                        if (nde == null)
                        {
                            result += "探伤类型[" + col5 + "]错误!" + "|";
                        }
                        else
                        {
                            ndeId = nde.DetectionTypeId;
                            t.DetectionTypeId = nde.DetectionTypeId;
                        }
                    }
                    else
                    {
                        result += "探伤类型此项为必填项!" + "|";
                    }
                    var pointBatchItem = trustIn.FirstOrDefault(x => x.InstallationId == installationId && x.WorkAreaId == workAreaId && x.PipelineId == pipelineId && x.WeldJointId == weldJointId && x.DetectionTypeId == ndeId);
                    if (pointBatchItem == null)
                    {
                        result += "检验批中不存在对应焊口信息" + "|";
                    }
                    else
                    {
                        if (pointBatchItem.TrustBatchItemId != null)
                        {
                            result += "焊口已委托" + "|";
                        }
                        else
                        {
                            t.IsWelderFirst = pointBatchItem.IsWelderFirst;
                        }
                    }
                    if (!string.IsNullOrEmpty(col6))
                    {
                        try
                        {
                            DateTime d = Convert.ToDateTime(col6);
                            t.TrustDate = d.Date;
                        }
                        catch (Exception)
                        {
                            result += "委托日期 [" + col6 + "]错误!" + "|";
                        }
                    }
                    else
                    {
                        result += "委托日期此项为必填项!" + "|";
                    }
                    if (!string.IsNullOrEmpty(col7))
                    {
                        Model.Base_Unit unit = Funs.DB.Base_Unit.FirstOrDefault(x => x.UnitCode == col7);
                        if (unit == null)
                        {
                            result += "检测单位编号[" + col7 + "]错误!" + "|";
                        }
                        else
                        {
                            t.NDEUuit = unit.UnitId;
                        }
                    }
                    else
                    {
                        result += "检测单位此项为必填项!" + "|";
                    }
                    if (!string.IsNullOrEmpty(col8))
                    {
                        if (col8 != "打磨" && col8 != "机加工" && col8 != "喷砂" && col8 != "漆面")
                        {
                            result += "表面检测需录入:打磨、机加工、喷砂、漆面" + "|";
                        }
                    }
                    if (!string.IsNullOrEmpty(col9))
                    {
                        if (col9 != "焊后" && col9 != "打磨后" && col9 != "热处理后" && col9 != "坡口准备" && col9 != "清根后" && col9 != "压力试验后" && col9 != "其他")
                        {
                            result += "检测时机需录入:焊后、打磨后、热处理后、坡口准备、清根后、压力试验后、其他" + "|";
                        }
                    }
                    log.Remark = result;
                    logListData.Add(log);
                    trustList.Add(t);
                }
                var trustCodeList = trustList.Select(p => p.TrustBatchCode).Distinct();
                foreach (var trustCode in trustCodeList)
                {
                    string result = string.Empty;
                    var t = from x in trustList where x.TrustBatchCode == trustCode select x;
                    var logInfo = logListData.FirstOrDefault(x => x.TrustBatchCode == trustCode);
                    if (t.Select(x => x.InstallationId).Distinct().Count() > 1)
                    {
                        result += "委托单" + trustCode + "装置不一至" + "|";
                    }
                    if (t.Select(x => x.WorkAreaId).Distinct().Count() > 1)
                    {
                        result += "委托单" + trustCode + "区域不一至" + "|";
                    }
                    if (t.Select(x => x.PipelineId).Distinct().Count() > 1)
                    {
                        result += "委托单" + trustCode + "管线不一至" + "|";
                    }
                    if (t.Select(x => x.WeldingMethodId).Distinct().Count() > 1)
                    {
                        result += "委托单" + trustCode + "焊接方法不一至" + "|";
                    }
                    if (t.Select(x => x.GrooveTypeId).Distinct().Count() > 1)
                    {
                        result += "委托单" + trustCode + "坡口类型不一至" + "|";
                    }
                    if (t.Select(x => x.DetectionTypeId).Distinct().Count() > 1)
                    {
                        result += "委托单" + trustCode + "探伤类型不一至" + "|";
                    }
                    if (t.Select(x => x.TrustDate).Distinct().Count() > 1)
                    {
                        result += "委托单" + trustCode + "委托日期不一至" + "|";
                    }
                    if (logInfo != null)
                    {
                        logInfo.Remark += result;
                    }
                }
                if (logListData.Where(t => t.Remark != "").Any())
                {
                    Funs.DB.TrustBatchImportErrorLog.InsertAllOnSubmit(logListData);
                    Funs.DB.SubmitChanges();
                    this.Grid1.Hidden = false;
                    this.BindGrid1(BatchNo);
                }
                else
                {
                    errorInfos = string.Empty;
                    lbResult.Text = "审核数据正确,请点击导入!";
                }
            }
        }
        private void BindGrid1(string batchNo)
        {
            var result = Funs.DB.TrustBatchImportErrorLog.Where(t => t.BatchNo == batchNo).OrderBy(t => t.RowID).ToList();
            this.Grid1.DataSource = result;
            this.Grid1.DataBind();
        }
        #endregion
        #region 导入
        /// 
        /// 导入
        /// 
        /// 
        /// 
        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.hdFileName.Text))
            {
                if (errorInfos == string.Empty)
                {
                    string IsXls = Path.GetExtension(this.fuAttachUrl.FileName).ToString().Trim().ToLower();
                    if (IsXls != ".xls" && IsXls != ".xlsx")
                    {
                        ShowNotify("只能选择Excel文件!", MessageBoxIcon.Warning);
                        return;
                    }
                    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);
                    if (ds.Tables.Count > 0)
                    {
                        string result = string.Empty;
                        List trustList = new List();
                        var units = from x in Funs.DB.Base_Unit select x;
                        var area = from x in Funs.DB.Project_WorkArea where x.ProjectId == this.CurrUser.LoginProjectId select x;
                        var installation = from x in Funs.DB.Project_Installation where x.ProjectId == this.CurrUser.LoginProjectId select x;
                        var trustIn = from x in Funs.DB.View_TrustBathcIn where x.ProjectId == this.CurrUser.LoginProjectId select x;
                        var pipeList = from x in Funs.DB.Pipeline_Pipeline where x.ProjectId == this.CurrUser.LoginProjectId select x;
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            string col0 = ds.Tables[0].Rows[i][0].ToString().Trim();
                            string col1 = ds.Tables[0].Rows[i][1].ToString().Trim();
                            string col2 = ds.Tables[0].Rows[i][2].ToString().Trim();
                            string col3 = ds.Tables[0].Rows[i][3].ToString().Trim();
                            string col4 = ds.Tables[0].Rows[i][4].ToString().Trim();
                            string col5 = ds.Tables[0].Rows[i][5].ToString().Trim();
                            string col6 = ds.Tables[0].Rows[i][6].ToString().Trim();
                            string col7 = ds.Tables[0].Rows[i][7].ToString().Trim();
                            string col8 = ds.Tables[0].Rows[i][8].ToString().Trim();
                            string col9 = ds.Tables[0].Rows[i][9].ToString().Trim();
                            Model.Batch_BatchTrust t = new Model.Batch_BatchTrust();
                            t.TrustBatchCode = col0;
                            Model.Project_Installation ins = installation.FirstOrDefault(x => x.InstallationCode == col1);
                            t.InstallationId = ins.InstallationId;
                            
                            Model.Project_WorkArea workArea = area.FirstOrDefault(x => x.WorkAreaCode == col2 && x.InstallationId == ins.InstallationId);
                            t.WorkAreaId = workArea.WorkAreaId;
                            var pipe = pipeList.FirstOrDefault(x => x.PipelineCode == col3 && x.WorkAreaId == workArea.WorkAreaId);
                            t.PipelineId = pipe.PipelineId;
                            t.UnitId = pipe.UnitId;
                            var jot = Funs.DB.Pipeline_WeldJoint.FirstOrDefault(x => x.PipelineId == pipe.PipelineId && x.WeldJointCode == col4);
                            t.QuaCertFile = jot.WeldJointId;  // 作为焊口ID
                            t.WeldingMethodId = jot.WeldingMethodId;
                            t.GrooveTypeId = jot.GrooveTypeId;
                            var nde = Funs.DB.Base_DetectionType.FirstOrDefault(x => x.DetectionTypeCode == col5);
                            t.DetectionTypeId = nde.DetectionTypeId;
                            var pointBatchItem = trustIn.FirstOrDefault(x => x.WorkAreaId == workArea.WorkAreaId && x.PipelineId == pipe.PipelineId && x.WeldJointId == jot.WeldJointId && x.DetectionTypeId == nde.DetectionTypeId);
                            t.IsWelderFirst = pointBatchItem.IsWelderFirst;
                            t.AcceptStandard = pointBatchItem.PointBatchItemId; // 作为点口明细ID
                            t.TopointBatch = pointBatchItem.PointBatchId;
                            t.TrustDate = Convert.ToDateTime(col6).Date;
                            Model.Base_Unit unit = Funs.DB.Base_Unit.FirstOrDefault(x => x.UnitCode == col7);
                            t.NDEUuit = unit.UnitId;
                            if (!string.IsNullOrEmpty(col8))
                            {
                                t.SurfaceState = col8;
                            }
                            else
                            {
                                t.SurfaceState = "打磨";
                            }
                            if (!string.IsNullOrEmpty(col9))
                            {
                                t.DetectionTiming = col9;
                            }
                            else
                            {
                                t.DetectionTiming = "焊后";
                            }
                            trustList.Add(t);
                        }
                        var trustCodeList = trustList.Select(p => p.TrustBatchCode).Distinct();
                        foreach (var trustCode in trustCodeList)
                        {
                            var t = from x in trustList where x.TrustBatchCode == trustCode select x;
                            Model.Batch_BatchTrust newBatchTrust = new Model.Batch_BatchTrust();
                            string trustBatchId = SQLHelper.GetNewID(typeof(Model.Batch_BatchTrust));
                            newBatchTrust.TrustBatchId = trustBatchId;
                            newBatchTrust.TrustBatchCode = trustCode;
                            newBatchTrust.TrustDate = t.First().TrustDate;
                            newBatchTrust.ProjectId = CurrUser.LoginProjectId;
                            newBatchTrust.UnitId = t.First().UnitId;
                            newBatchTrust.InstallationId = t.First().InstallationId;
                            newBatchTrust.WorkAreaId = t.First().WorkAreaId;
                            newBatchTrust.WeldingMethodId = t.First().WeldingMethodId;
                            newBatchTrust.GrooveTypeId = t.First().GrooveTypeId;
                            newBatchTrust.IsWelderFirst = t.First().IsWelderFirst;
                            newBatchTrust.DetectionTypeId = t.First().DetectionTypeId;
                            newBatchTrust.PipelineId = t.First().PipelineId;
                            newBatchTrust.TopointBatch = t.First().TopointBatch;
                            BLL.Batch_BatchTrustService.AddBatchTrust(newBatchTrust);  // 新增委托单
                            // 生成委托明细,并回写点口明细信息
                            foreach (var p in t)
                            {
                                Model.Batch_BatchTrustItem trustItem = new Model.Batch_BatchTrustItem
                                {
                                    TrustBatchItemId = SQLHelper.GetNewID(typeof(Model.Batch_BatchTrustItem)),
                                    TrustBatchId = trustBatchId,
                                    PointBatchItemId = p.AcceptStandard,
                                    WeldJointId = p.QuaCertFile,
                                    //FilmNum = fileNum,
                                    CreateDate = p.TrustDate
                                };
                                Batch_BatchTrustItemService.AddBatchTrustItem(trustItem);
                                var pointItem = BLL.Batch_PointBatchItemService.GetPointBatchItemByPointBatchItemId(p.AcceptStandard);
                                pointItem.PointDate = p.TrustDate;
                                pointItem.PointState = "1";
                                pointItem.IsBuildTrust = true;
                                pointItem.GLGSAudit = Const.GlyId; // 导入时默认为管理员
                                pointItem.JLAudit = Const.GlyId;
                                Funs.DB.SubmitChanges();
                            }
                            // 导入后该批次里所有口都关闭
                            var pointItemList = (from x in Funs.DB.Batch_PointBatchItem where x.PointBatchId == newBatchTrust.TopointBatch && (x.IsCompletedPoint == null || x.IsCompletedPoint == false) select x).ToList();
                            foreach (var item in pointItemList)
                            {
                                item.IsCompletedPoint = true;
                            }
                            Funs.DB.SubmitChanges();
                        }
                        ShowNotify("导入成功!", MessageBoxIcon.Success);
                    }
                    else
                    {
                        ShowNotify("无记录!", MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    ShowNotify("请修正错误数据后再导入!", MessageBoxIcon.Warning);
                }
            }
            else
            {
                ShowNotify("请先审核要导入的文件!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 导出错误提示
        /// 
        /// 导出错误提示
        /// 
        /// 
        /// 
        protected void btnOut_Click(object sender, EventArgs e)
        {
            string rootPath = Server.MapPath("~/") + Const.ExcelUrl;
            //模板文件
            string TempletFileName = rootPath + "TrustErrorOut.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 JointComprehensive
            XSSFSheet reportModel = (XSSFSheet)hssfworkbook.GetSheet("Sheet1");
            XSSFFont cs_content_Font1 = (XSSFFont)hssfworkbook.CreateFont(); //创建字体
            cs_content_Font1.FontName = "sans-serif";//字体
            cs_content_Font1.FontHeightInPoints = 9; //字体大小
            ICellStyle style = hssfworkbook.CreateCellStyle();
            style.SetFont(cs_content_Font1);
            XSSFFont cs_content_Font = (XSSFFont)hssfworkbook.CreateFont(); //创建字体
            cs_content_Font.FontName = "sans-serif";//字体
            cs_content_Font.FontHeightInPoints = 10; //字体大小
            cs_content_Font.Color = HSSFColor.Red.Index;
            IDataFormat dataformat = hssfworkbook.CreateDataFormat();
            ICellStyle styleDate = hssfworkbook.CreateCellStyle();
            styleDate.SetFont(cs_content_Font1);
            styleDate.DataFormat = dataformat.GetFormat("yyyy-mm-dd");
            // 排序
            var result = Funs.DB.TrustBatchImportErrorLog.Where(t => t.BatchNo == this.BatchCode).OrderBy(t => t.RowID).ToList();
            if (result.Count > 0)
            {
                var rowIndex = 1;
                foreach (var itemOver in result)
                {
                    if (reportModel.GetRow(rowIndex) == null) reportModel.CreateRow(rowIndex);
                    #region 列赋值
                    //行号
                    if (reportModel.GetRow(rowIndex).GetCell(0) == null) reportModel.GetRow(rowIndex).CreateCell(0);
                    reportModel.GetRow(rowIndex).GetCell(0).SetCellValue(itemOver.RowID.ToString());
                    reportModel.GetRow(rowIndex).GetCell(0).CellStyle = style; //将字体绑定到样式
                    //委托单
                    if (reportModel.GetRow(rowIndex).GetCell(1) == null) reportModel.GetRow(rowIndex).CreateCell(1);
                    reportModel.GetRow(rowIndex).GetCell(1).SetCellValue(itemOver.TrustBatchCode);
                    reportModel.GetRow(rowIndex).GetCell(1).CellStyle = style;
                    //装置
                    if (reportModel.GetRow(rowIndex).GetCell(2) == null) reportModel.GetRow(rowIndex).CreateCell(2);
                    reportModel.GetRow(rowIndex).GetCell(2).SetCellValue(itemOver.InstallCode);
                    reportModel.GetRow(rowIndex).GetCell(2).CellStyle = style;
                    //区域
                    if (reportModel.GetRow(rowIndex).GetCell(3) == null) reportModel.GetRow(rowIndex).CreateCell(3);
                    reportModel.GetRow(rowIndex).GetCell(3).SetCellValue(itemOver.AreaCode);
                    reportModel.GetRow(rowIndex).GetCell(3).CellStyle = style;
                    //管线号
                    if (reportModel.GetRow(rowIndex).GetCell(4) == null) reportModel.GetRow(rowIndex).CreateCell(4);
                    reportModel.GetRow(rowIndex).GetCell(4).SetCellValue(itemOver.PipelineCode);
                    reportModel.GetRow(rowIndex).GetCell(4).CellStyle = style;
                    //焊口号
                    if (reportModel.GetRow(rowIndex).GetCell(5) == null) reportModel.GetRow(rowIndex).CreateCell(5);
                    reportModel.GetRow(rowIndex).GetCell(5).SetCellValue(itemOver.WeldJointCode);
                    reportModel.GetRow(rowIndex).GetCell(5).CellStyle = style;
                    //探伤类型
                    if (reportModel.GetRow(rowIndex).GetCell(6) == null) reportModel.GetRow(rowIndex).CreateCell(6);
                    reportModel.GetRow(rowIndex).GetCell(6).SetCellValue(itemOver.DetectionType);
                    reportModel.GetRow(rowIndex).GetCell(6).CellStyle = style;
                    //委托日期
                    if (reportModel.GetRow(rowIndex).GetCell(7) == null) reportModel.GetRow(rowIndex).CreateCell(7);
                    reportModel.GetRow(rowIndex).GetCell(7).SetCellValue(itemOver.TrustDate);
                    reportModel.GetRow(rowIndex).GetCell(7).CellStyle = style;
                    //检测单位
                    if (reportModel.GetRow(rowIndex).GetCell(8) == null) reportModel.GetRow(rowIndex).CreateCell(8);
                    reportModel.GetRow(rowIndex).GetCell(8).SetCellValue(itemOver.UnitCode);
                    reportModel.GetRow(rowIndex).GetCell(8).CellStyle = style;
                    //表面
                    if (reportModel.GetRow(rowIndex).GetCell(9) == null) reportModel.GetRow(rowIndex).CreateCell(9);
                    reportModel.GetRow(rowIndex).GetCell(9).SetCellValue(itemOver.SurfaceState);
                    reportModel.GetRow(rowIndex).GetCell(9).CellStyle = style;
                    //检测时机
                    if (reportModel.GetRow(rowIndex).GetCell(10) == null) reportModel.GetRow(rowIndex).CreateCell(10);
                    reportModel.GetRow(rowIndex).GetCell(10).SetCellValue(itemOver.Opportunity);
                    reportModel.GetRow(rowIndex).GetCell(10).CellStyle = style;
                    //错误
                    if (reportModel.GetRow(rowIndex).GetCell(11) == null) reportModel.GetRow(rowIndex).CreateCell(11);
                    reportModel.GetRow(rowIndex).GetCell(11).SetCellValue(itemOver.Remark.Replace("|",","));
                    reportModel.GetRow(rowIndex).GetCell(11).CellStyle = style;
                    #endregion
                    rowIndex++;
                }
            }
            #endregion
            reportModel.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=委托单错误日志_" + 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();
            //Response.ClearContent();
            //string filename = Funs.GetNewFileName();
            //Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(Resources.Lan.JointComprehensive + 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 = 10000;
            BindGrid1(this.BatchCode);
            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 html = row.Values[column.ColumnIndex].ToString();
                    if (column.ColumnID == "Remark")
                    {
                        html = (row.FindControl("lablRemark") as AspNet.Label).Text;
                    }
                    sb.AppendFormat("| {0} | ", html);
                }
                sb.Append("
");
            }
            sb.Append("
");
            return sb.ToString();
        }
        /// 
        /// 重载VerifyRenderingInServerForm方法,否则运行的时候会出现如下错误提示:“类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内”
        /// 
        /// 
        public override void VerifyRenderingInServerForm(Control control)
        {
        }
        #endregion
        #region 下载模板
        /// 
        /// 下载模板按钮
        /// 
        /// 
        /// 
        protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Confirm.GetShowReference("确定下载导入模板吗?", String.Empty, MessageBoxIcon.Question, PageManager1.GetCustomEventReference(false, "Confirm_OK"), PageManager1.GetCustomEventReference("Confirm_Cancel")));
        }
        /// 
        /// 下载导入模板
        /// 
        /// 
        /// 
        protected void PageManager1_CustomEvent(object sender, CustomEventArgs e)
        {
            if (e.EventArgument == "Confirm_OK")
            {
                string rootPath = Server.MapPath("~/");
                string uploadfilepath = rootPath + Const.HJGL_TrustInTemplateUrl;
                //string filePath = Const.HJGL_TrustInTemplateUrl;
                //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("委托单模板.xlsx", 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
    }
}