using Aspose.Words;
using Aspose.Words.Tables;
using BLL;
using FineUIPro.Web.BaseInfo;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
namespace FineUIPro.Web.CQMS.ProcessControl
{
    public partial class InspectionNotice : PageBase
    {
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetButtonPower();
                if (this.CurrUser.UserId == BLL.Const.hfnbdId)
                {
                    this.drpCNProfessional.DataTextField = "DetectionItems";
                    this.drpCNProfessional.DataValueField = "ControlId";
                    this.drpCNProfessional.DataSource = BLL.CNProfessionalService.GetCnProList();
                    this.drpCNProfessional.DataBind();
                    Funs.FineUIPleaseSelect(this.drpCNProfessional);
                }
                else
                {
                    BLL.CNProfessionalService.InitCNProfessionalDownList(this.drpCNProfessional, true);//专业
                }
                BLL.UnitService.InitUnitByProjectIdUnitTypeDropDownList(drpUnit, this.CurrUser.LoginProjectId, BLL.Const.ProjectUnitType_2, true);//施工分包商
                BindGrid();
            }
        }
        /// 
        /// 数据绑定
        /// 
        public void BindGrid()
        {
            DataTable tb = BindData();
            Grid1.RecordCount = tb.Rows.Count;
            //tb = GetFilteredTable(Grid1.FilteredData, tb);
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
            //if (this.CurrUser.UserId == BLL.Const.hfnbdId)
            //{
            //    string strSql = @"SELECT P.InspectionId,P.ProjectId,P.UnitId,
            //                        P.CNProfessionalId,
            //                        P.UnitWorkId,U.UnitName,
            //                        C.DetectionItems as ProfessionalName,
            //                        P.NoticeCode,UnitWork.UnitWorkName,
            //                        DP.DivisionName AS Branch,
            //                        BP.BreakdownName AS ControlPointType,
            //                        BP.Class,P.AcceptanceSite, P.AcceptanceCheckMan"
            //                    + @" FROM ProcessControl_InspectionManagement AS P"
            //                    + @" LEFT JOIN Base_Unit AS U ON U.UnitId = P.UnitId"
            //                    + @" LEFT JOIN Control_PointCropping C ON C.ControlId = P.CNProfessionalId"
            //                    + @" LEFT JOIN WBS_UnitWork AS UnitWork ON UnitWork.UnitWorkId = P.UnitWorkId"
            //                    + @" LEFT JOIN WBS_DivisionProject AS DP ON DP.DivisionProjectId = P.Branch"
            //                    + @" LEFT JOIN WBS_BreakdownProject AS BP ON BP.BreakdownProjectId = P.ControlPointType"
            //                    + @" WHERE P.ProjectId=@ProjectId ";
            //    List listStr = new List();
            //    listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            //    if (drpUnit.SelectedValue != BLL.Const._Null)
            //    {
            //        strSql += " AND P.UnitId=@UnitId";
            //        listStr.Add(new SqlParameter("@UnitId", drpUnit.SelectedValue));
            //    }
            //    if (drpCNProfessional.SelectedValue != BLL.Const._Null)
            //    {
            //        strSql += " AND P.CNProfessionalId=@CNProfessionalId";
            //        listStr.Add(new SqlParameter("@CNProfessionalId", drpCNProfessional.SelectedValue));
            //    }
            //    if (!string.IsNullOrEmpty(txtStarTime.Text.Trim()))
            //    {
            //        strSql += " AND P.InspectionDate >= @startTime";
            //        listStr.Add(new SqlParameter("@startTime", Funs.GetNewDateTime(txtStarTime.Text.Trim())));
            //    }
            //    if (!string.IsNullOrEmpty(txtEndTime.Text.Trim()))
            //    {
            //        strSql += " AND P.InspectionDate <= @endTime";
            //        listStr.Add(new SqlParameter("@endTime", Funs.GetNewDateTime(txtEndTime.Text.Trim())));
            //    }
            //    SqlParameter[] parameter = listStr.ToArray();
            //    DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            //    Grid1.RecordCount = tb.Rows.Count;
            //    //tb = GetFilteredTable(Grid1.FilteredData, tb);
            //    var table = this.GetPagedDataTable(Grid1, tb);
            //    Grid1.DataSource = table;
            //    Grid1.DataBind();
            //}
            //else
            //{
            //    string strSql = @"SELECT P.InspectionId,P.ProjectId,P.UnitId,
            //                        P.CNProfessionalId,
            //                        P.UnitWorkId,U.UnitName,
            //                        C.ProfessionalName as ProfessionalName,
            //                        P.NoticeCode,UnitWork.UnitWorkName,
            //                        DP.DivisionName AS Branch,
            //                        BP.BreakdownName AS ControlPointType,
            //                        BP.Class,P.AcceptanceSite,P.AcceptanceCheckMan"
            //                    + @" FROM ProcessControl_InspectionManagement AS P"
            //                    + @" LEFT JOIN Base_Unit AS U ON U.UnitId = P.UnitId"
            //                    + @" left join Base_CNProfessional c on c.CNProfessionalId = P.CNProfessionalId"
            //                    + @" LEFT JOIN WBS_UnitWork AS UnitWork ON UnitWork.UnitWorkId = P.UnitWorkId"
            //                    + @" LEFT JOIN WBS_DivisionProject AS DP ON DP.DivisionProjectId = P.Branch"
            //                    + @" LEFT JOIN WBS_BreakdownProject AS BP ON BP.BreakdownProjectId = P.ControlPointType"
            //                    + @" WHERE P.ProjectId=@ProjectId ";
            //    List listStr = new List();
            //    listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            //    if (drpUnit.SelectedValue != BLL.Const._Null)
            //    {
            //        strSql += " AND P.UnitId=@UnitId";
            //        listStr.Add(new SqlParameter("@UnitId", drpUnit.SelectedValue));
            //    }
            //    if (drpCNProfessional.SelectedValue != BLL.Const._Null)
            //    {
            //        strSql += " AND P.CNProfessionalId=@CNProfessionalId";
            //        listStr.Add(new SqlParameter("@CNProfessionalId", drpCNProfessional.SelectedValue));
            //    }
            //    if (!string.IsNullOrEmpty(txtStarTime.Text.Trim()))
            //    {
            //        strSql += " AND P.InspectionDate >= @startTime";
            //        listStr.Add(new SqlParameter("@startTime", Funs.GetNewDateTime(txtStarTime.Text.Trim())));
            //    }
            //    if (!string.IsNullOrEmpty(txtEndTime.Text.Trim()))
            //    {
            //        strSql += " AND P.InspectionDate <= @endTime";
            //        listStr.Add(new SqlParameter("@endTime", Funs.GetNewDateTime(txtEndTime.Text.Trim())));
            //    }
            //    SqlParameter[] parameter = listStr.ToArray();
            //    DataTable tb = SQLHelper.GetDataTableRunText(strSql, parameter);
            //    Grid1.RecordCount = tb.Rows.Count;
            //    //tb = GetFilteredTable(Grid1.FilteredData, tb);
            //    var table = this.GetPagedDataTable(Grid1, tb);
            //    Grid1.DataSource = table;
            //    Grid1.DataBind();
            //}
        }
        /// 
        /// 查询数据
        /// 
        /// 
        public DataTable BindData()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT P.InspectionId,P.ProjectId,P.UnitId,P.CNProfessionalId,P.UnitWorkId,U.UnitName,C.ProfessionalName as ProfessionalName,P.NoticeCode,UnitWork.UnitWorkName,DP.DivisionName AS Branch,BP.BreakdownName AS ControlPointType,BP.Class,P.AcceptanceSite,P.AcceptanceCheckMan ");
            sb.Append("FROM ProcessControl_InspectionManagement AS P ");
            sb.Append("LEFT JOIN Base_Unit AS U ON U.UnitId = P.UnitId ");
            sb.Append("LEFT JOIN Base_CNProfessional AS C on c.CNProfessionalId = P.CNProfessionalId ");
            sb.Append("LEFT JOIN WBS_UnitWork AS UnitWork ON UnitWork.UnitWorkId = P.UnitWorkId ");
            sb.Append("LEFT JOIN WBS_DivisionProject AS DP ON DP.DivisionProjectId = P.Branch ");
            sb.Append("LEFT JOIN WBS_BreakdownProject AS BP ON BP.BreakdownProjectId = P.ControlPointType ");
            sb.Append("WHERE P.ProjectId=@ProjectId ");
            List listStr = new List();
            listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            if (drpUnit.SelectedValue != BLL.Const._Null)
            {
                sb.Append("AND P.UnitId=@UnitId ");
                listStr.Add(new SqlParameter("@UnitId", drpUnit.SelectedValue));
            }
            if (drpCNProfessional.SelectedValue != BLL.Const._Null)
            {
                sb.Append("AND P.CNProfessionalId=@CNProfessionalId ");
                listStr.Add(new SqlParameter("@CNProfessionalId", drpCNProfessional.SelectedValue));
            }
            if (!string.IsNullOrEmpty(txtStarTime.Text.Trim()))
            {
                sb.Append("AND P.InspectionDate >= @startTime ");
                listStr.Add(new SqlParameter("@startTime", Funs.GetNewDateTime(txtStarTime.Text.Trim())));
            }
            if (!string.IsNullOrEmpty(txtEndTime.Text.Trim()))
            {
                sb.Append("AND P.InspectionDate <= @endTime ");
                listStr.Add(new SqlParameter("@endTime", Funs.GetNewDateTime(txtEndTime.Text.Trim())));
            }
            if (!string.IsNullOrEmpty(txtCompileDateS.Text.Trim()))
            {
                sb.Append("AND P.CompileDate >= @CompileDateS ");
                listStr.Add(new SqlParameter("@CompileDateS", Funs.GetNewDateTime(txtCompileDateS.Text.Trim())));
            }
            if (!string.IsNullOrEmpty(txtCompileDateE.Text.Trim()))
            {
                sb.Append("AND P.CompileDate <= @CompileDateE ");
                listStr.Add(new SqlParameter("@CompileDateE", Funs.GetNewDateTime(txtCompileDateE.Text.Trim())));
            }
            sb.Append("ORDER BY P.NoticeCode DESC ");
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(sb.ToString(), parameter);
            return tb;
        }
        #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();
        }
        #endregion
        #region 增加
        /// 
        /// 新增按钮事件
        /// 
        /// 
        /// 
        protected void btnNew_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("InspectionNoticeEdit.aspx", "编辑 - ")));
        }
        #endregion
        #region 编辑
        /// 
        /// Grid行双击事件
        /// 
        /// 
        /// 
        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            btnMenuModify_Click(null, null);
        }
        /// 
        ///右键编辑
        /// 
        /// 
        /// 
        protected void btnMenuModify_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录", MessageBoxIcon.Warning);
                return;
            }
            //合格的情况下不允许修改
            //var model = Funs.DB.ProcessControl_InspectionManagement.FirstOrDefault(x => x.InspectionId == Grid1.SelectedRowID);
            //if (model.IsOnceQualified == true)
            //{
            //    Alert.ShowInTop("该共检通知单已合格,不允许修改!", MessageBoxIcon.Warning);
            //    return;
            //}
            PageContext.RegisterStartupScript(Window1.GetShowReference(String.Format("InspectionNoticeEdit.aspx?InspectionId={0}", Grid1.SelectedRowID, "编辑 - ")));
        }
        #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();
                    var InspectionEquipment = BLL.InspectionManagementService.GetInspectionManagementById(rowID);
                    if (InspectionEquipment != null)
                    {
                        BLL.InspectionManagementDetailService.DeleteAllInspectionDetail(rowID);
                        BLL.InspectionManagementService.DeleteInspectionManagement(rowID);
                    }
                }
                BindGrid();
                ShowNotify("删除数据成功!", MessageBoxIcon.Success);
            }
        }
        #endregion
        #region 获取按钮权限
        /// 
        /// 获取按钮权限
        /// 
        /// 
        /// 
        private void GetButtonPower()
        {
            if (Request.Params["value"] == "0")
            {
                return;
            }
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.LoginProjectId, this.CurrUser.UserId, BLL.Const.InspectionNoticeMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnAdd))
                {
                    this.btnNew.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnModify))
                {
                    this.btnMenuModify.Hidden = false;
                    this.Grid1.EnableRowDoubleClickEvent = true;
                }
                else
                {
                    this.Grid1.EnableRowDoubleClickEvent = false;
                }
                if (buttonList.Contains(BLL.Const.BtnDelete))
                {
                    this.btnMenuDel.Hidden = false;
                }
                if (buttonList.Contains(BLL.Const.BtnSave))
                {
                    this.btnMenuCopy.Hidden = false;
                }
            }
        }
        #endregion
        #region 导出按钮
        /// 导出按钮
        /// 
        /// 
        /// 
        protected void btnOut_Click(object sender, EventArgs e)
        {
            string rootPath = Server.MapPath("~/");
            string initTemplatePath = Const.InspectionNoticesTempUrl;
            string uploadfilepath = string.Empty;
            string newUrl = string.Empty;
            uploadfilepath = rootPath + initTemplatePath;
            var db = Funs.DB;
            var lists = (from x in db.ProcessControl_InspectionManagement
                         join bu in db.Base_Unit on x.UnitId equals bu.UnitId into buGroup
                         from bu in buGroup.DefaultIfEmpty()
                         join bcn in db.Base_CNProfessional on x.CNProfessionalId equals bcn.CNProfessionalId into bcnGroup
                         from bcn in bcnGroup.DefaultIfEmpty()
                         //join wbsuw in db.WBS_UnitWork on x.UnitWorkId equals wbsuw.UnitWorkId into wbsuwGroup
                         //from wbsuw in wbsuwGroup.DefaultIfEmpty()
                         //join wbsd in db.WBS_DivisionProject on x.Branch equals wbsd.DivisionProjectId into wbsdGroup
                         //from wbsd in wbsdGroup.DefaultIfEmpty()
                         //join wbsbp in db.WBS_BreakdownProject on x.ControlPointType equals wbsbp.BreakdownProjectId into wbsbpGroup
                         //from wbsbp in wbsbpGroup.DefaultIfEmpty()
                         where x.ProjectId == this.CurrUser.LoginProjectId
                         orderby x.NoticeCode descending
                         select new
                         {
                             UnitId = x.UnitId,
                             UnitName = bu.UnitName,
                             CNProfessionalId = x.CNProfessionalId,
                             ProfessionalName = bcn.ProfessionalName,
                             NoticeCode = x.NoticeCode,
                             AcceptanceSite = x.AcceptanceSite,
                             AcceptanceCheckMan = x.AcceptanceCheckMan,
                             InspectionDate = x.InspectionDate
                         });
            if (drpUnit.SelectedValue != BLL.Const._Null)
            {
                lists = lists.Where(x => x.UnitId == drpUnit.SelectedValue);
            }
            if (drpCNProfessional.SelectedValue != BLL.Const._Null)
            {
                lists = lists.Where(x => x.CNProfessionalId == drpCNProfessional.SelectedValue);
            }
            if (!string.IsNullOrEmpty(txtStarTime.Text.Trim()))
            {
                lists = lists.Where(x => x.InspectionDate >= Funs.GetNewDateTime(txtStarTime.Text.Trim()));
            }
            if (!string.IsNullOrEmpty(txtEndTime.Text.Trim()))
            {
                lists = lists.Where(x => x.InspectionDate <= Funs.GetNewDateTime(txtEndTime.Text.Trim()));
            }
            if (lists != null)
            {
                string projectName = BLL.ProjectService.GetShortNameByProjectId(this.CurrUser.LoginProjectId);
                newUrl = uploadfilepath.Replace("共检通知单模板", "共检通知单(" + projectName.Replace("/", "") + DateTime.Now.ToString("yyyyMMdd") + ")");
                if (File.Exists(newUrl))
                {
                    File.Delete(newUrl);
                }
                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);
                    workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(stream);
                }
                // 创建单元格样式
                NPOI.SS.UserModel.ICellStyle cellStyle = workbook.CreateCellStyle();
                cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
                cellStyle.WrapText = true;//自动换行
                var font = workbook.CreateFont();
                font.FontHeightInPoints = 11;
                cellStyle.SetFont(font);
                // 第二步:创建新数据行
                NPOI.SS.UserModel.ISheet sheet = workbook.GetSheetAt(0);
                NPOI.SS.UserModel.IRow row = sheet.GetRow(0);
                NPOI.SS.UserModel.ICell cell;
                int i = 2;
                foreach (var item in lists)
                {
                    // 第二步:创建新数据行
                    row = sheet.CreateRow(i);
                    // 添加数据
                    cell = row.CreateCell(0);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.UnitName);//施工分包商
                    cell = row.CreateCell(1);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.ProfessionalName);//专业
                    cell = row.CreateCell(2);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.NoticeCode);//共检通知单编号
                    cell = row.CreateCell(3);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.AcceptanceSite);//验收部位
                    cell = row.CreateCell(4);
                    cell.CellStyle = cellStyle;
                    string userName = string.Empty;
                    if (!string.IsNullOrEmpty(item.AcceptanceCheckMan))
                    {
                        userName = ConvertCheckMan(item.AcceptanceCheckMan);
                    }
                    cell.SetCellValue(userName);//检查人
                    i++;
                }
                // 第三步:写入文件流
                using (FileStream stream = new FileStream(newUrl, FileMode.Create, FileAccess.Write))
                {
                    workbook.Write(stream);
                    workbook.Close();
                }
                string fileName = Path.GetFileName(newUrl);
                FileInfo info = new FileInfo(newUrl);
                long fileSize = info.Length;
                Response.Clear();
                Response.ContentType = "application/x-zip-compressed";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                Response.AddHeader("Content-Length", fileSize.ToString());
                Response.TransmitFile(newUrl, 0, fileSize);
                Response.Flush();
                Response.Close();
                File.Delete(newUrl);
            }
            else
            {
                Alert.ShowInTop("当前无记录,无法导出!", MessageBoxIcon.Warning);
            }
        }
        protected void btnOut_Click2(object sender, EventArgs e)
        {
            string rootPath = Server.MapPath("~/");
            string initTemplatePath = Const.InspectionNoticesTempUrl;
            string uploadfilepath = string.Empty;
            string newUrl = string.Empty;
            uploadfilepath = rootPath + initTemplatePath;
            var lists = (from x in Funs.DB.ProcessControl_InspectionManagementDetail
                         join y in Funs.DB.ProcessControl_InspectionManagement
                         on x.InspectionId equals y.InspectionId
                         where y.ProjectId == this.CurrUser.LoginProjectId
                         select y);
            if (drpUnit.SelectedValue != BLL.Const._Null)
            {
                lists = lists.Where(x => x.UnitId == drpUnit.SelectedValue);
            }
            if (drpCNProfessional.SelectedValue != BLL.Const._Null)
            {
                lists = lists.Where(x => x.CNProfessionalId == drpCNProfessional.SelectedValue);
            }
            if (!string.IsNullOrEmpty(txtStarTime.Text.Trim()))
            {
                lists = lists.Where(x => x.InspectionDate >= Funs.GetNewDateTime(txtStarTime.Text.Trim()));
            }
            if (!string.IsNullOrEmpty(txtEndTime.Text.Trim()))
            {
                lists = lists.Where(x => x.InspectionDate <= Funs.GetNewDateTime(txtEndTime.Text.Trim()));
            }
            if (lists != null)
            {
                string projectName = BLL.ProjectService.GetShortNameByProjectId(this.CurrUser.LoginProjectId);
                newUrl = uploadfilepath.Replace("共检通知单模板", "共检通知单(" + projectName.Replace("/", "") + DateTime.Now.ToString("yyyyMMdd") + ")");
                if (File.Exists(newUrl))
                {
                    File.Delete(newUrl);
                }
                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);
                    workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(stream);
                }
                // 创建单元格样式
                NPOI.SS.UserModel.ICellStyle cellStyle = workbook.CreateCellStyle();
                cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
                cellStyle.WrapText = true;//自动换行
                var font = workbook.CreateFont();
                font.FontHeightInPoints = 11;
                cellStyle.SetFont(font);
                // 第二步:创建新数据行
                NPOI.SS.UserModel.ISheet sheet = workbook.GetSheetAt(0);
                NPOI.SS.UserModel.IRow row = sheet.GetRow(0);
                NPOI.SS.UserModel.ICell cell;
                int i = 2;
                foreach (var item in lists)
                {
                    // 第二步:创建新数据行
                    row = sheet.CreateRow(i);
                    // 添加数据
                    cell = row.CreateCell(0);
                    cell.CellStyle = cellStyle;
                    string unitName = string.Empty;
                    if (!string.IsNullOrEmpty(item.UnitId))
                    {
                        unitName = BLL.UnitService.GetUnitNameByUnitId(item.UnitId);
                    }
                    cell.SetCellValue(unitName);//施工分包商
                    cell = row.CreateCell(1);
                    cell.CellStyle = cellStyle;
                    string proName = string.Empty;
                    var cnp = BLL.CNProfessionalService.GetCNProfessional(item.CNProfessionalId);
                    if (cnp != null)
                    {
                        proName = cnp.ProfessionalName;
                    }
                    cell.SetCellValue(proName);//专业
                    cell = row.CreateCell(2);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.NoticeCode);//共检通知单编号
                    cell = row.CreateCell(3);
                    cell.CellStyle = cellStyle;
                    cell.SetCellValue(item.AcceptanceSite);//验收部位
                    cell = row.CreateCell(4);
                    cell.CellStyle = cellStyle;
                    string userName = string.Empty;
                    if (!string.IsNullOrEmpty(item.AcceptanceCheckMan))
                    {
                        userName = ConvertCheckMan(item.AcceptanceCheckMan);
                    }
                    cell.SetCellValue(userName);//检查人
                    i++;
                }
                // 第三步:写入文件流
                using (FileStream stream = new FileStream(newUrl, FileMode.Create, FileAccess.Write))
                {
                    workbook.Write(stream);
                    workbook.Close();
                }
                string fileName = Path.GetFileName(newUrl);
                FileInfo info = new FileInfo(newUrl);
                long fileSize = info.Length;
                Response.Clear();
                Response.ContentType = "application/x-zip-compressed";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                Response.AddHeader("Content-Length", fileSize.ToString());
                Response.TransmitFile(newUrl, 0, fileSize);
                Response.Flush();
                Response.Close();
                File.Delete(newUrl);
            }
            else
            {
                Alert.ShowInTop("当前无记录,无法导出!", MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 导出详细
        protected void btnPrinter_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录!", MessageBoxIcon.Warning);
                return;
            }
            string Id = Grid1.SelectedRowID;
            try
            {
                string rootPath = Server.MapPath("~/");
                string initTemplatePath = string.Empty;
                string uploadfilepath = string.Empty;
                string newUrl = string.Empty;
                string filePath = string.Empty;
                Model.SGGLDB db = Funs.DB;
                initTemplatePath = Const.InspectionTemplateUrl;
                uploadfilepath = rootPath + initTemplatePath;
                newUrl = uploadfilepath.Replace(".doc", "(" + Funs.GetNewFileName() + ")" + ".doc");
                if (File.Exists(newUrl))
                {
                    File.Delete(newUrl);
                }
                File.Copy(uploadfilepath, newUrl);
                //更新书签内容
                Document doc = new Aspose.Words.Document(newUrl);
                DocumentBuilder builder = new DocumentBuilder(doc);
                #region 头部静态列
                //业主单位
                Bookmark bookmarkUnitName = doc.Range.Bookmarks["unitName"];
                if (bookmarkUnitName != null)
                {
                    var units = (from x in db.Base_Unit
                                 join y in db.Project_ProjectUnit
                                 on x.UnitId equals y.UnitId
                                 where y.ProjectId == this.CurrUser.LoginProjectId && y.UnitType == BLL.Const.ProjectUnitType_4
                                 orderby x.UnitName
                                 select x).FirstOrDefault();
                    if (units != null)
                    {
                        bookmarkUnitName.Text = units.UnitName;
                    }
                }
                var projectModel = db.Base_Project.Where(x => x.ProjectId == this.CurrUser.LoginProjectId).FirstOrDefault();
                var inspectionModel = db.ProcessControl_InspectionManagement.Where(x => x.InspectionId == Id).FirstOrDefault();
                //项目编号
                Bookmark bookmarkProjectCode = doc.Range.Bookmarks["projectCode"];
                if (bookmarkProjectCode != null)
                {
                    if (projectModel != null)
                    {
                        bookmarkProjectCode.Text = projectModel.ProjectCode;
                    }
                }
                //项目名称
                Bookmark bookmarkProjectName = doc.Range.Bookmarks["projectName"];
                if (bookmarkProjectName != null)
                {
                    if (projectModel != null)
                    {
                        bookmarkProjectName.Text = projectModel.ProjectName;
                    }
                }
                //共检编号
                Bookmark bookmarkInspectionCode = doc.Range.Bookmarks["inspectionCode"];
                if (bookmarkInspectionCode != null)
                {
                    if (inspectionModel != null && !string.IsNullOrEmpty(inspectionModel.NoticeCode))
                    {
                        bookmarkInspectionCode.Text = inspectionModel.NoticeCode;
                    }
                }
                //施工分包商名称
                Bookmark bookmarkunitNamefbs = doc.Range.Bookmarks["unitNamefbs"];
                if (bookmarkunitNamefbs != null)
                {
                    var valModel = db.Base_Unit.Where(x => x.UnitId == inspectionModel.UnitId).FirstOrDefault();
                    if (inspectionModel != null && valModel != null)
                    {
                        bookmarkunitNamefbs.Text = valModel.UnitName;
                    }
                }
                //编制人
                Bookmark bookmarkcompileMan = doc.Range.Bookmarks["compileMan"];
                if (bookmarkcompileMan != null)
                {
                    var valModel = db.Sys_User.Where(x => x.UserId == inspectionModel.CompileMan).FirstOrDefault();
                    if (inspectionModel != null && valModel != null)
                    {
                        bookmarkcompileMan.Text = valModel.UserName;
                    }
                }
                //总承包商名称
                Bookmark bookmarkunitNamezcb = doc.Range.Bookmarks["unitNamezcb"];
                if (bookmarkunitNamezcb != null)
                {
                    var units = (from x in db.Base_Unit
                                 join y in db.Project_ProjectUnit
                                 on x.UnitId equals y.UnitId
                                 where y.ProjectId == this.CurrUser.LoginProjectId && y.UnitType == BLL.Const.ProjectUnitType_1
                                 orderby x.UnitName
                                 select x).FirstOrDefault();
                    if (units != null)
                    {
                        bookmarkunitNamezcb.Text = units.UnitName;
                    }
                }
                //共检时间
                Bookmark bookmarkinspectionDate = doc.Range.Bookmarks["inspectionDate"];
                if (bookmarkinspectionDate != null)
                {
                    if (inspectionModel != null)
                    {
                        bookmarkinspectionDate.Text = inspectionModel.InspectionDate.ToString().Replace("/", "-");
                    }
                }
                //共检地点
                Bookmark bookmarkacceptanceSite = doc.Range.Bookmarks["acceptanceSite"];
                if (bookmarkacceptanceSite != null)
                {
                    if (inspectionModel != null)
                    {
                        bookmarkacceptanceSite.Text = inspectionModel.AcceptanceSite;
                    }
                }
                //涉及的单位/分部
                Bookmark bookmarkmanagementDetail = doc.Range.Bookmarks["managementDetail"];
                if (bookmarkmanagementDetail != null)
                {
                    //查询子表数据
                    var managementDetailval = "";
                    var valModelList = db.ProcessControl_InspectionManagementDetail.Where(x => x.InspectionId == Id).ToList();
                    if (valModelList != null)
                    {
                        int i = 0;
                        List vlist = new List();
                        foreach (var item in valModelList)
                        {
                            WorkBranchList modelWorkBranch = new WorkBranchList();
                            if (i > 0)
                            {
                                vlist.Select(x => x.Branch == item.Branch && x.UnitWorkId == item.UnitWorkId).ToList();
                                if (vlist.Count == 0)
                                {
                                    //没有相同数据
                                    modelWorkBranch.Branch = item.Branch;
                                    modelWorkBranch.UnitWorkId = item.UnitWorkId;
                                    vlist.Add(modelWorkBranch);
                                    managementDetailval += ConvertUnitWork(item.UnitWorkId) + "/" + ConvertBranch(item.Branch) + ",";
                                }
                            }
                            else
                            {
                                modelWorkBranch.Branch = item.Branch;
                                modelWorkBranch.UnitWorkId = item.UnitWorkId;
                                vlist.Add(modelWorkBranch);
                                managementDetailval += ConvertUnitWork(item.UnitWorkId) + "/" + ConvertBranch(item.Branch) + ",";
                            }
                            i += 1;
                        }
                        managementDetailval = managementDetailval.Substring(0, managementDetailval.Length - 1);
                    }
                    bookmarkmanagementDetail.Text = managementDetailval;
                }
                #endregion
                #region 质量检查内容、控制点等级、质量检查
                //项目总体施工进度情况
                builder.MoveToBookmark("tab");
                builder.StartTable();
                builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single;
                builder.CellFormat.Borders.Color = System.Drawing.Color.Black;
                builder.Bold = false;
                builder.RowFormat.Height = 20;
                builder.Font.Size = 10;
                var ManagementDetaillList = db.ProcessControl_InspectionManagementDetail.Where(x => x.InspectionId == Id).ToList();
                if (ManagementDetaillList != null)
                {
                    int i = 1;
                    foreach (var item in ManagementDetaillList)
                    {
                        //质量检查内容
                        builder.InsertCell();
                        if (ManagementDetaillList.Count <= 9)
                        {
                            builder.RowFormat.Height = 200 / ManagementDetaillList.Count;
                        }
                        else
                        {
                            builder.RowFormat.Height = 20;
                        }
                        builder.CellFormat.Borders.Left.LineWidth = 1;
                        builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                        builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                        builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                        builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                        builder.CellFormat.Width = 156;
                        builder.Write(ConvertControlPointType(item.ControlPointType));
                        builder.CellFormat.Borders.Left.LineWidth = 0;
                        // 控制点等级
                        builder.InsertCell();
                        builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                        builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                        builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                        builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                        builder.CellFormat.Width = 106;
                        var ControlPointType = ConvertClass(item.ControlPointType);
                        #region 控制点等级
                        if (ControlPointType.Contains("A"))
                        {
                            builder.Write("■A  ");
                        }
                        else
                        {
                            builder.Write("□A  ");
                        }
                        if (ControlPointType.Contains("B"))
                        {
                            builder.Write("■B  ");
                        }
                        else
                        {
                            builder.Write("□B  ");
                        }
                        if (ControlPointType.Contains("C"))
                        {
                            builder.Write("■C  ");
                        }
                        else
                        {
                            builder.Write("□C  ");
                        }
                        #endregion
                        //质量检查依据
                        builder.InsertCell();
                        builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                        builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                        builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                        builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                        builder.CellFormat.Width = 113.5;
                        var ControlBasis = ConvertBasis(item.ControlPointType);
                        builder.Write(ControlBasis);
                        //合并单元格
                        builder.InsertCell();
                        builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
                        builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                        builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Top;//垂直居中对齐
                        builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;//水平居中对齐
                        builder.CellFormat.Width = 112;
                        builder.Write("\r总承包商:\r     □ H   □ W\r");
                        builder.Write("监理:\r     □ H   □ W\r");
                        builder.Write("业主:\r     □ H   □ W\r");
                        builder.Write("质量监督:\r     □ H   □ W\r");
                        i += 1;
                        builder.EndRow();
                    }
                }
                builder.RowFormat.Height = 20;
                #endregion
                #region 底部静态
                //签收单位	总承包商	监理单位	业主	质量监督
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.ParagraphFormat.LineSpacing = 12; //设置1倍行距 12就是一倍行距
                builder.CellFormat.Width = 75.1;
                builder.Write("签收单位");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("总承包商");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("监理单位");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("业主");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("质量监督");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 112;
                builder.Write("");
                builder.EndRow();
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("签收人");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 112;
                builder.Write("");
                builder.EndRow();
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("签收日期");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 75.1;
                builder.Write("");
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                builder.CellFormat.Width = 112;
                builder.Write("");
                builder.EndRow();
                builder.InsertCell();
                builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.First;
                builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Top;//垂直居中对齐
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;//水平居中对齐
                builder.CellFormat.Width = 487.5;
                builder.ParagraphFormat.LineSpacing = 16; //设置1倍行距 12就是一倍行距
                builder.Write("备注:\r\r验收意见:\r总承包商意见:           □合格  □不合格\r监理意见:               □合格  □不合格\r业主意见:               □合格  □不合格\r                                                                          ");
                #region 生成二维码
                string imageUrl = Funs.RootPath + CreateQRCodeService.CreateCode_Simple("InspectionNotice$" + Id);
                if (File.Exists(imageUrl))
                {
                    builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;//水平居中对齐
                    builder.InsertImage(imageUrl, 100, 100);
                }
                #endregion
                builder.EndRow();
                builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;//水平居中对齐
                builder.Write("注:如果业主有规定,执行业主的规定。                                     ");
                #endregion
                doc.Save(newUrl);
                string fileName = Path.GetFileName(newUrl);
                FileInfo info = new FileInfo(newUrl);
                long fileSize = info.Length;
                Response.Clear();
                Response.ContentType = "application/x-zip-compressed";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                Response.AddHeader("Content-Length", fileSize.ToString());
                Response.TransmitFile(newUrl, 0, fileSize);
                Response.Flush();
                Response.Close();
                File.Delete(newUrl);
            }
            catch (Exception ex)
            {
                Alert.ShowInTop(ex.Message, MessageBoxIcon.Warning);
                return;
            }
        }
        public class WorkBranchList
        {
            public string UnitWorkId { get; set; }
            public string Branch { get; set; }
        }
        #region 转换字符串
        /// 
        /// 获取单位工程
        /// 
        /// 
        /// 
        protected string ConvertUnitWork(object UnitWorkId)
        {
            string name = string.Empty;
            if (UnitWorkId != null)
            {
                Model.WBS_UnitWork unitWork = BLL.UnitWorkService.GetUnitWorkByUnitWorkId(UnitWorkId.ToString());
                if (unitWork != null)
                {
                    name = unitWork.UnitWorkName;
                }
            }
            return name;
        }
        /// 
        /// 获取分部
        /// 
        /// 
        /// 
        protected string ConvertBranch(object Branch)
        {
            string name = string.Empty;
            if (Branch != null)
            {
                var branch = BLL.DivisionProjectService.GetDivisionProjectById(Branch.ToString());
                if (branch != null)
                {
                    name = branch.DivisionName;
                }
            }
            return name;
        }
        /// 
        /// 获取控制点内容
        /// 
        /// 
        /// 
        protected string ConvertControlPointType(object ControlPointType)
        {
            string name = string.Empty;
            if (ControlPointType != null)
            {
                var controlPointType = BLL.BreakdownProjectService.GetBreakdownProjectById(ControlPointType.ToString());
                if (controlPointType != null)
                {
                    name = controlPointType.BreakdownName;
                }
            }
            return name;
        }
        /// 
        /// 获取控制点等级
        /// 
        /// 
        /// 
        protected string ConvertClass(object ControlPointType)
        {
            string name = string.Empty;
            if (ControlPointType != null)
            {
                var controlPointType = BLL.BreakdownProjectService.GetBreakdownProjectById(ControlPointType.ToString());
                if (controlPointType != null)
                {
                    name = controlPointType.Class;
                }
            }
            return name;
        }
        /// 
        /// 获取执行依据
        /// 
        /// 
        /// 
        protected string ConvertBasis(object ControlPointType)
        {
            string name = string.Empty;
            if (ControlPointType != null)
            {
                var controlPointType = BLL.BreakdownProjectService.GetBreakdownProjectById(ControlPointType.ToString());
                if (controlPointType != null)
                {
                    name = controlPointType.Basis;
                }
            }
            return name;
        }
        /// 
        /// 获取检查人名称
        /// 
        /// 
        /// 
        protected string ConvertCheckMan(object CarryUnitIds)
        {
            var uname = BLL.UserService.getUserNamesUserIds(CarryUnitIds);
            if (string.IsNullOrEmpty(uname))
            {
                uname = CarryUnitIds.ToString();
            }
            return uname;
        }
        #endregion
        #endregion
        /// 
        /// 复制
        /// 
        /// 
        /// 
        protected void btnMenuCopy_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length == 0)
            {
                Alert.ShowInTop("请至少选择一条记录", MessageBoxIcon.Warning);
                return;
            }
            var inspection = BLL.InspectionManagementService.GetInspectionManagementById(this.Grid1.SelectedRowID);
            if (inspection != null)
            {
                Model.ProcessControl_InspectionManagement newInspection = new Model.ProcessControl_InspectionManagement();
                newInspection.InspectionId = SQLHelper.GetNewID(typeof(Model.ProcessControl_InspectionManagement));
                newInspection.ProjectId = this.CurrUser.LoginProjectId;
                newInspection.UnitId = inspection.UnitId;
                newInspection.CNProfessionalId = inspection.CNProfessionalId;
                newInspection.InspectionCode = inspection.InspectionCode;
                newInspection.UnitWorkId = inspection.UnitWorkId;
                newInspection.Branch = inspection.Branch;
                newInspection.ControlPointType = inspection.ControlPointType;
                newInspection.AcceptanceSite = inspection.AcceptanceSite;
                newInspection.IsOnceQualified = inspection.IsOnceQualified;
                newInspection.InspectionDate = inspection.InspectionDate;
                newInspection.AttachUrl = inspection.AttachUrl;
                newInspection.CheckDate = inspection.CheckDate;
                newInspection.CheckMan = inspection.CheckMan;
                newInspection.UnqualifiedReason = inspection.UnqualifiedReason;
                //通知单编号后有字母递增,无则加“a”
                string fisrtE = inspection.NoticeCode.Substring(0, inspection.NoticeCode.Length - 1);
                string lastE = inspection.NoticeCode.Substring(inspection.NoticeCode.Length - 1, 1);
                bool b = Regex.IsMatch(lastE, "[a-zA-Z]");
                if (b)
                {
                    int x = (int)Convert.ToByte(Convert.ToChar(lastE));
                    newInspection.NoticeCode = fisrtE + Convert.ToChar(x + 1);
                }
                else
                {
                    newInspection.NoticeCode = inspection.NoticeCode + "a";
                }
                newInspection.AcceptanceCheckMan = inspection.AcceptanceCheckMan;
                newInspection.ParentDivisionProjectId = inspection.ParentDivisionProjectId;
                newInspection.CompileMan = this.CurrUser.UserId;
                newInspection.CompileDate = DateTime.Now;
                newInspection.FileType = inspection.FileType;
                newInspection.AttachUrl2 = inspection.AttachUrl2;
                BLL.InspectionManagementService.AddInspectionManagement(newInspection);
                var details = InspectionManagementDetailService.GetInspectionDetails(inspection.InspectionId);
                if (details.Count > 0)
                {
                    foreach (var item in details)
                    {
                        Model.ProcessControl_InspectionManagementDetail newDetail = new Model.ProcessControl_InspectionManagementDetail();
                        newDetail.InspectionDetailId = SQLHelper.GetNewID(typeof(Model.ProcessControl_InspectionManagementDetail));
                        newDetail.InspectionId = newInspection.InspectionId;
                        newDetail.UnitWorkId = item.UnitWorkId;
                        newDetail.Branch = item.Branch;
                        newDetail.ControlPointType = item.ControlPointType;
                        newDetail.CreateDate = DateTime.Now;
                        BLL.InspectionManagementDetailService.AddInspectionDetail(newDetail);
                    }
                }
                ShowNotify("复制成功!");
                BindGrid();
            }
        }
    }
}