using BLL;
using BLL.Common;
using BLL.CQMS.Comprehensive;
using FineUIPro.Web.AttachFile;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.Streaming.Values;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Services.Description;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
namespace FineUIPro.Web.Transfer
{
    public partial class PunchlistFrom : PageBase
    {
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetButtonPower();
                BLL.PunchlistFromService.InitTurnoverSystemCodeUnitDropDownList(this.drpTurnoverSystemCode, this.CurrUser.LoginProjectId, false);
                BLL.PunchlistFromService.InitActionByUnitDropDownList(this.ddlAction_By, this.CurrUser.LoginProjectId, false);
                BLL.PunchlistFromService.InitPICDropDownList(this.ddlPIC, this.CurrUser.LoginProjectId, false);//责任人PIC
                BLL.PunchlistFromService.InitWUHPICDropDownList(this.ddlPIC_WUH, this.CurrUser.LoginProjectId, false);//责任人-五环/PIC-WUH
                BLL.PunchlistFromService.InitDiscDropDownList(this.ddlDisc, this.CurrUser.LoginProjectId, false);//Disc
                BindGrid();
                this.btnNew.OnClientClick = Window1.GetShowReference("PunchlistFromEdit.aspx") + "return false;";
            }
        }
        public DataTable DataSql()
        {
            string strSql = @"select * ,(CASE isnull(IsEng,0) WHEN 1 THEN 'Y' ELSE 'N' END) IsEngStr ,IsMatI IsMatIStr
                            from Transfer_PunchlistFrom
                            where ProjectId = @ProjectId";
            List listStr = new List();
            listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            if (!string.IsNullOrEmpty(this.txtRaised_By.Text.Trim()))
            {
                strSql += " AND Raised_By = @Raised_By";
                listStr.Add(new SqlParameter("@Raised_By", this.txtRaised_By.Text.Trim()));
            }
            if (!string.IsNullOrEmpty(this.txtNo.Text.Trim()))
            {
                strSql += " AND Num_NO = @No";
                listStr.Add(new SqlParameter("@No", this.txtNo.Text.Trim()));
            }
            if (!string.IsNullOrEmpty(this.txtSystem_No.Text.Trim()))
            {
                strSql += " AND System_No like @System_No";
                listStr.Add(new SqlParameter("@System_No", "%" + this.txtSystem_No.Text.Trim() + "%"));
            }
            //if (!string.IsNullOrEmpty(this.txtSub_Sys_No.Text.Trim()))
            //{
            //    strSql += " AND Sub_Sys_No like @Sub_Sys_No";
            //    listStr.Add(new SqlParameter("@Sub_Sys_No", "%" + this.txtSub_Sys_No.Text.Trim() + "%"));
            //}
            if (this.drpTurnoverSystemCode.SelectedItemArray.Count() > 1 || (this.drpTurnoverSystemCode.SelectedValue != BLL.Const._Null && this.drpTurnoverSystemCode.SelectedItemArray.Count() == 1))
            {
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in this.drpTurnoverSystemCode.SelectedValueArray)
                {
                    if (!string.IsNullOrEmpty(item) && item != BLL.Const._Null)
                    {
                        strSql += " OR Sub_Sys_No = @Sub_Sys_No" + i.ToString();
                        listStr.Add(new SqlParameter("@Sub_Sys_No" + i.ToString(), item));
                    }
                    i++;
                }
                strSql += ")";
            }
            if (!string.IsNullOrEmpty(txtStartDate_Raised.Text.Trim()))
            {
                strSql += " AND Date_Raised = @StartDate_Raised";
                listStr.Add(new SqlParameter("@StartDate_Raised", Funs.GetNewDateTime(txtStartDate_Raised.Text.Trim())));
            }
            //if (!string.IsNullOrEmpty(txtStartDate_Raised.Text.Trim()))
            //{
            //    strSql += " AND Date_Raised >= @StartDate_Raised";
            //    listStr.Add(new SqlParameter("@StartDate_Raised", Funs.GetNewDateTime(txtStartDate_Raised.Text.Trim())));
            //}
            //if (!string.IsNullOrEmpty(txtEndDate_Raised.Text.Trim()))
            //{
            //    strSql += " AND Date_Raised <= @EndDate_Raised";
            //    listStr.Add(new SqlParameter("@EndDate_Raised", Funs.GetNewDateTime(txtEndDate_Raised.Text.Trim())));
            //}
            //if (!string.IsNullOrEmpty(txtStartRequired_Date.Text.Trim()))
            //{
            //    strSql += " AND Required_Date >= @StartRequired_Date";
            //    listStr.Add(new SqlParameter("@StartRequired_Date", Funs.GetNewDateTime(txtStartRequired_Date.Text.Trim())));
            //}
            if (!string.IsNullOrEmpty(txtEndRequired_Date.Text.Trim()))
            {
                strSql += " AND Required_Date <= @EndRequired_Date";
                listStr.Add(new SqlParameter("@EndRequired_Date", Funs.GetNewDateTime(txtEndRequired_Date.Text.Trim())));
            }
            //if (!string.IsNullOrEmpty(txtStartActual_Date.Text.Trim()))
            //{
            //    strSql += " AND Actual_Date >= @StartActual_Date";
            //    listStr.Add(new SqlParameter("@StartActual_Date", Funs.GetNewDateTime(txtStartActual_Date.Text.Trim())));
            //}
            //if (!string.IsNullOrEmpty(txtEndActual_Date.Text.Trim()))
            //{
            //    strSql += " AND Actual_Date <= @EndActual_Date";
            //    listStr.Add(new SqlParameter("@EndActual_Date", Funs.GetNewDateTime(txtEndActual_Date.Text.Trim())));
            //}
            if (this.ddlDisc.SelectedItemArray.Count() > 1 || (this.ddlDisc.SelectedValue != BLL.Const._Null && this.ddlDisc.SelectedItemArray.Count() == 1))
            {
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in this.ddlDisc.SelectedValueArray)
                {
                    if (!string.IsNullOrEmpty(item) && item != BLL.Const._Null)
                    {
                        strSql += " OR Disc = @Disc" + i.ToString();
                        listStr.Add(new SqlParameter("@Disc" + i.ToString(), item));
                    }
                    i++;
                }
                strSql += ")";
            }
            // if (!string.IsNullOrEmpty(txtDisc.Text.Trim()))
            // {
            //     strSql += " AND Disc = @Disc";
            //     listStr.Add(new SqlParameter("@Disc", txtDisc.Text.Trim()));
            // }
            if (!string.IsNullOrEmpty(ddlEng.SelectedValue.Trim()))
            {
                strSql += " AND IsEng = @IsEng";
                listStr.Add(new SqlParameter("@IsEng", ddlEng.SelectedValue.Trim() == "Y" ? 1 : 0));
            }
            if (!string.IsNullOrEmpty(ddlMatI.SelectedValue.Trim()))
            {
                strSql += " AND IsMatI = @IsMatI";
                listStr.Add(new SqlParameter("@IsMatI", ddlMatI.SelectedValue.Trim()));
            }
            if (!string.IsNullOrEmpty(ddlPunchType.SelectedValue.Trim()))
            {
                strSql += " AND Punch_Type = @Punch_Type";
                listStr.Add(new SqlParameter("@Punch_Type", ddlPunchType.SelectedValue.Trim()));
            }
            if (!string.IsNullOrEmpty(ddlCat.SelectedValue.Trim()))
            {
                strSql += " AND Cat = @Cat";
                listStr.Add(new SqlParameter("@Cat", ddlCat.SelectedValue.Trim()));
            }
            //if (!string.IsNullOrEmpty(txtAction_By.Text.Trim()))
            //{
            //    strSql += " AND Action_By = @Action_By";
            //    listStr.Add(new SqlParameter("@Action_By", txtAction_By.Text.Trim()));
            //}
            //if (ddlAction_By.SelectedValue != null && ddlAction_By.SelectedValue != BLL.Const._Null)
            //{
            //    strSql += " AND Action_By = @Action_By";
            //    listStr.Add(new SqlParameter("@Action_By", ddlAction_By.SelectedValue.Trim()));
            //}
            if (this.ddlAction_By.SelectedItemArray.Count() > 1 || (this.ddlAction_By.SelectedValue != BLL.Const._Null && this.ddlAction_By.SelectedItemArray.Count() == 1))
            {
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in this.ddlAction_By.SelectedValueArray)
                {
                    if (!string.IsNullOrEmpty(item) && item != BLL.Const._Null)
                    {
                        strSql += " OR Action_By = @Action_By" + i.ToString();
                        listStr.Add(new SqlParameter("@Action_By" + i.ToString(), item));
                    }
                    i++;
                }
                strSql += ")";
            }
            if (this.ddlPIC.SelectedItemArray.Count() > 1 || (this.ddlPIC.SelectedValue != BLL.Const._Null && this.ddlPIC.SelectedItemArray.Count() == 1))
            {
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in this.ddlPIC.SelectedValueArray)
                {
                    if (!string.IsNullOrEmpty(item) && item != BLL.Const._Null)
                    {
                        strSql += " OR PIC = @PIC" + i.ToString();
                        listStr.Add(new SqlParameter("@PIC" + i.ToString(), item));
                    }
                    i++;
                }
                strSql += ")";
            }
            if (this.ddlPIC_WUH.SelectedItemArray.Count() > 1 || (this.ddlPIC_WUH.SelectedValue != BLL.Const._Null && this.ddlPIC_WUH.SelectedItemArray.Count() == 1))
            {
                strSql += " AND (1=2 ";
                int i = 0;
                foreach (var item in this.ddlPIC_WUH.SelectedValueArray)
                {
                    if (!string.IsNullOrEmpty(item) && item != BLL.Const._Null)
                    {
                        strSql += " OR PIC_WUH = @PIC_WUH" + i.ToString();
                        listStr.Add(new SqlParameter("@PIC_WUH" + i.ToString(), item));
                    }
                    i++;
                }
                strSql += ")";
            }
            //if (ddlAction_By.SelectedValue != null && ddlAction_By.SelectedValue != BLL.Const._Null)
            //{
            //    strSql += " AND Action_By = @Action_By";
            //    listStr.Add(new SqlParameter("@Action_By", ddlAction_By.SelectedValue.Trim()));
            //}
            // if (!string.IsNullOrEmpty(txtPIC.Text.Trim()))
            // {
            //     strSql += " AND PIC like @PIC";
            //     listStr.Add(new SqlParameter("@PIC", "%" + this.txtPIC.Text.Trim() + "%"));
            // }
            // if (!string.IsNullOrEmpty(txtPIC_WUH.Text.Trim()))
            // {
            //     strSql += " AND PIC_WUH like @PIC_WUH";
            //     listStr.Add(new SqlParameter("@PIC_WUH", "%" + this.txtPIC_WUH.Text.Trim() + "%"));
            // }
            if (!string.IsNullOrEmpty(ddlStatus.SelectedValue.Trim()))
            {
                strSql += " AND Status = @Status";
                listStr.Add(new SqlParameter("@Status", ddlStatus.SelectedValue.Trim()));
            }
            strSql += " order by Num_No ";
            SqlParameter[] parameter = listStr.ToArray();
            return SQLHelper.GetDataTableRunText(strSql, parameter);
        }
        /// 
        /// 数据绑定
        /// 
        public void BindGrid()
        {
            DataTable tb = DataSql();
            Grid1.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        #endregion
        #region 分页、排序
        /// 
        /// 分页下拉
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }
        /// 
        /// 分页索引事件
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            BindGrid();
        }
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, FineUIPro.GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid();
        }
        #endregion
        #region 查询
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 关闭弹出窗口
        /// 
        /// 关闭弹出窗口
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid();
        }
        protected void WindowAtt_Close(object sender, WindowCloseEventArgs e)
        {
            BindGrid();
        }
        #endregion
        #region 删除
        /// 
        /// 右键删除
        /// 
        /// 
        /// 
        protected void btnMenuDel_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    Model.Transfer_PunchlistFrom model = Funs.DB.Transfer_PunchlistFrom.FirstOrDefault(x => x.Id == rowID);
                    if (model != null)
                    {
                        Funs.DB.Transfer_PunchlistFrom.DeleteOnSubmit(model);
                        Funs.DB.SubmitChanges();
                    }
                }
                BindGrid();
                ShowNotify("删除数据成功!", MessageBoxIcon.Success);
            }
        }
        #endregion
        #region Photoes附件
        /// 
        /// 右键附件上传功能
        /// 
        /// 
        /// 
        protected void btnMenuAttachA_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../AttachFile/webuploader.aspx?type=0&toKeyId={0}_A&path=FileUpload/Transfer/PunchlistFrom&menuId={1}", Grid1.SelectedRowID, BLL.Const.PunchlistFromMenuId)));
            }
        }
        #endregion
        #region Corrected_Photos附件
        /// 
        /// 右键附件上传功能
        /// 
        /// 
        /// 
        protected void btnMenuAttachB_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../AttachFile/webuploader.aspx?type=0&toKeyId={0}_B&path=FileUpload/Transfer/PunchlistFrom&menuId={1}", Grid1.SelectedRowID, BLL.Const.PunchlistFromMenuId)));
            }
        }
        #endregion
        /// 
        /// 获取附件(放于Img中)
        /// 
        /// 
        /// 
        protected string ConvertImageUrlByImage(object Id_type)
        {
            string url = string.Empty;
            if (Id_type != null)
            {
                var registration = BLL.AttachFileService.GetAttachFile(Id_type.ToString(), BLL.Const.PunchlistFromMenuId);
                if (registration != null)
                {
                    url = BLL.UploadAttachmentService.ShowImage("../../", registration.AttachUrl);
                }
            }
            return url;
        }
        #region 导入
        /// 
        /// 导入按钮
        /// 
        /// 
        /// 
        protected void btnImport_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("PunchlistFromDataIn.aspx", "导入 - ")));
        }
        #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("尾项" + filename, System.Text.Encoding.UTF8) + ".xls");
        //    Response.ContentType = "application/excel";
        //    Response.ContentEncoding = System.Text.Encoding.UTF8;
        //    this.Grid1.PageSize = 100000;
        //    this.BindGrid();
        //    Response.Write(GetGridMultiHeaderTableHtml(Grid1));
        //    //Response.Write(GetGridTableHtml(Grid1));
        //    Response.End();
        //}
        #endregion
        #region 清空数据
        /// 
        /// 清空数据
        /// 
        /// 
        /// 
        protected void btnClear_Click(object sender, EventArgs e)
        {
            var ProjectId = this.CurrUser.LoginProjectId;
            if (!string.IsNullOrWhiteSpace(ProjectId))
            {
                string strSql = $"delete from  Transfer_PunchlistFrom where ProjectId = '{ProjectId}';";
                BLL.SQLHelper.ExecutSql(strSql);
                BindGrid();
            }
        }
        #endregion
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            if (Request.Params["value"] == "0")
            {
                return;
            }
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.PunchlistFromMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    this.btnNew.Hidden = false;
                    btnMenuAttachA.Hidden = false;
                    btnMenuAttachB.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnMenuModify.Hidden = false;
                    this.Grid1.EnableRowDoubleClickEvent = true;
                    btnMenuAttachA.Hidden = false;
                    btnMenuAttachB.Hidden = false;
                }
                else
                {
                    this.Grid1.EnableRowDoubleClickEvent = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnMenuDel.Hidden = false;
                    this.btnClear.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnSave))
                {
                    this.btnImport.Hidden = false;
                }
            }
        }
        #endregion
        #region 编辑
        /// 
        /// 右键编辑事件
        /// 
        /// 
        /// 
        protected void btnMenuModify_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string id = Grid1.SelectedRowID;
            var accidentPersonRecord = Funs.DB.Transfer_PunchlistFrom.FirstOrDefault(p => p.Id == id);
            if (accidentPersonRecord == null)
            {
                Alert.ShowInTop("修改的数据已经不存在,请检查!", MessageBoxIcon.Warning);
                return;
            }
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("PunchlistFromEdit.aspx?Id={0}", id, "编辑 - ")));
        }
        #endregion
        /// 导出按钮
        /// 
        /// 
        /// 
        protected void btnOut_Click(object sender, EventArgs e)
        {
            string rootPath = Server.MapPath("~/");
            string initTemplatePath = string.Empty;
            string uploadfilepath = string.Empty;
            string newUrl = string.Empty;
            string filePath = string.Empty;
            initTemplatePath = "File\\Excel\\DataOut\\PunchlistFrom导出模板.xlsx";
            uploadfilepath = rootPath + initTemplatePath;
            DataTable tb = DataSql();
            if (tb.Rows.Count <= 0)
            {
                ShowNotify("没有要导出的数据!!!", MessageBoxIcon.Warning);
                return;
            }
            try
            {
                newUrl = uploadfilepath.Replace("DataOut", "PunchlistFrom").Replace("导出模板", "导出数据").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);
                }
                NPOI.SS.UserModel.ICellStyle cellStyleC = workbook.CreateCellStyle();
                cellStyleC.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyleC.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyleC.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyleC.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyleC.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                cellStyleC.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
                cellStyleC.WrapText = true;
                NPOI.SS.UserModel.ISheet sheet = workbook.GetSheetAt(0);
                //var pcList = Funs.DB.AttachFile.Where(p => p.MenuId == BLL.Const.PunchlistFromMenuId && p.AttachUrl != null && p.AttachUrl != "").ToList();
                var pcList = new List();
                if (rbOutType.SelectedValue == "1")
                {//导出带图片
                    pcList = Funs.DB.AttachFile.Where(p => p.MenuId == BLL.Const.PunchlistFromMenuId && p.AttachUrl != null && p.AttachUrl != "").ToList();
                }
                int i = 2;
                foreach (DataRow tbRow in tb.Rows)
                {
                    string Id = tbRow["Id"].ToString();
                    NPOI.SS.UserModel.IRow row = sheet.CreateRow(i);
                    NPOI.SS.UserModel.ICell cell;
                    cell = row.CreateCell(0);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Num_NO"] == null ? "" : tbRow["Num_NO"].ToString());
                    cell = row.CreateCell(1);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["System_No"] == null ? "" : tbRow["System_No"].ToString());
                    cell = row.CreateCell(2);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Sub_Sys_No"] == null ? "" : tbRow["Sub_Sys_No"].ToString());
                    cell = row.CreateCell(3);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["DESCRIPTION"] == null ? "" : tbRow["DESCRIPTION"].ToString());
                    //Photoes附件
                    var photoesUrl = pcList.FirstOrDefault(p => p.ToKeyId == $"{Id}_A");
                    if (photoesUrl != null && !string.IsNullOrWhiteSpace(photoesUrl.AttachUrl))
                    {
                        string[] arrUrl = photoesUrl.AttachUrl.Split(',');
                        sheet.SetColumnWidth(4, 30 * 256);
                        row.Height = (short)(90 * 20 * arrUrl.Length);
                        foreach (string url in arrUrl)
                        {
                            var oneUrl = Server.MapPath("~/") + url;
                            byte[] bytes = System.IO.File.ReadAllBytes(oneUrl);
                            int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
                            // 第三步:创建画部
                            IDrawing patriarch = sheet.CreateDrawingPatriarch();
                            // 第四步:设置锚点
                            int rowline = 1; // y方向
                                             // 参数说明:(在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格列数,行数,终止单元格列数,行数)  
                            IClientAnchor anchor = patriarch.CreateAnchor(0, 0, 0, 0, 4, i, 5, i + 1);
                            // 第五步:把图片插到相应的位置+1
                            IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);
                            //就取第一张,如果后期想取全部 那把下面这个跳出语句去掉
                            break;
                        }
                    }
                    cell = row.CreateCell(5);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Cat"] == null ? "" : tbRow["Cat"].ToString());
                    cell = row.CreateCell(6);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Raised_By"] == null ? "" : tbRow["Raised_By"].ToString());
                    cell = row.CreateCell(7);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Date_Raised"] == DBNull.Value ? "" : Convert.ToDateTime(tbRow["Date_Raised"]).ToString("yyyy-MM-dd"));
                    cell = row.CreateCell(8);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Disc"] == null ? "" : tbRow["Disc"].ToString());
                    cell = row.CreateCell(9);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["IsEngStr"] == null ? "" : tbRow["IsEngStr"].ToString());
                    cell = row.CreateCell(10);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["IsMatIStr"] == null ? "" : tbRow["IsMatIStr"].ToString());
                    cell = row.CreateCell(11);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Punch_Type"] == null ? "" : tbRow["Punch_Type"].ToString());
                    cell = row.CreateCell(12);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Required_Date"] == DBNull.Value ? "" : Convert.ToDateTime(tbRow["Required_Date"]).ToString("yyyy-MM-dd"));
                    cell = row.CreateCell(13);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Action_By"] == null ? "" : tbRow["Action_By"].ToString());
                    cell = row.CreateCell(14);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["PIC"] == null ? "" : tbRow["PIC"].ToString());
                    cell = row.CreateCell(15);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["PIC_WUH"] == null ? "" : tbRow["PIC_WUH"].ToString());
                    cell = row.CreateCell(16);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Correction_Action"] == null ? "" : tbRow["Correction_Action"].ToString());
                    //CorrectedPhotos附件
                    var correctedPhotosUrl = pcList.FirstOrDefault(p => p.ToKeyId == $"{Id}_B");
                    if (correctedPhotosUrl != null && !string.IsNullOrWhiteSpace(correctedPhotosUrl.AttachUrl))
                    {
                        string[] arrUrl = correctedPhotosUrl.AttachUrl.Split(',');
                        sheet.SetColumnWidth(17, 30 * 256);
                        row.Height = (short)(90 * 20);
                        foreach (string url in arrUrl)
                        {
                            var oneUrl = Server.MapPath("~/") + url;
                            byte[] bytes = System.IO.File.ReadAllBytes(oneUrl);
                            int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
                            // 第三步:创建画部
                            IDrawing patriarch = sheet.CreateDrawingPatriarch();
                            // 第四步:设置锚点
                            int rowline = 1; // y方向
                                             // 参数说明:(在起始单元格的X坐标0-1023,Y的坐标0-255,在终止单元格的X坐标0-1023,Y的坐标0-255,起始单元格列数,行数,终止单元格列数,行数)  
                            IClientAnchor anchor = patriarch.CreateAnchor(0, 0, 0, 0, 17, i, 18, i + 1);
                            // 第五步:把图片插到相应的位置+1
                            IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);
                            //就取第一张,如果后期想取全部 那把下面这个跳出语句去掉
                            break;
                        }
                    }
                    cell = row.CreateCell(18);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Actual_Date"] == DBNull.Value ? "" : Convert.ToDateTime(tbRow["Actual_Date"]).ToString("yyyy-MM-dd"));
                    cell = row.CreateCell(19);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Cleared_By"] == null ? "" : tbRow["Cleared_By"].ToString());
                    cell = row.CreateCell(20);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Cleared_Date"] == DBNull.Value ? "" : Convert.ToDateTime(tbRow["Cleared_Date"]).ToString("yyyy-MM-dd"));
                    cell = row.CreateCell(21);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Confirmed_By"] == null ? "" : tbRow["Confirmed_By"].ToString());
                    cell = row.CreateCell(22);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Confirmed_Date"] == DBNull.Value ? "" : Convert.ToDateTime(tbRow["Confirmed_Date"]).ToString("yyyy-MM-dd"));
                    cell = row.CreateCell(23);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Verified_By"] == null ? "" : tbRow["Verified_By"].ToString());
                    cell = row.CreateCell(24);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Verified_Date"] == DBNull.Value ? "" : Convert.ToDateTime(tbRow["Verified_Date"]).ToString("yyyy-MM-dd"));
                    cell = row.CreateCell(25);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Status"] == null ? "" : tbRow["Status"].ToString());
                    cell = row.CreateCell(26);
                    cell.CellStyle = cellStyleC;
                    cell.SetCellValue(tbRow["Remark"] == null ? "" : tbRow["Remark"].ToString());
                    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();
            }
            catch (WebException ex)
            {
            }
            finally
            {
                if (File.Exists(newUrl))
                {
                    File.Delete(newUrl);
                }
            }
        }
    }
}