using BLL;
using Model;
using Newtonsoft.Json.Linq;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
namespace FineUIPro.Web.TestRun.BeforeTestRun
{
    public partial class InspectWanderAboutConfirm : PageBase
    {
        /// 
        /// 检查表主键
        /// 
        public string SubInspectId
        {
            get { return (string)ViewState["SubInspectId"]; }
            set { ViewState["SubInspectId"] = value; }
        }
        /// 
        /// 类型
        /// 
        public int ConfirmType
        {
            get { return (int)ViewState["ConfirmType"]; }
            set { ViewState["ConfirmType"] = value; }
        }
        /// 
        /// 类型名称
        /// 
        public string ConfirmTypeName
        {
            get { return (string)ViewState["ConfirmTypeName"]; }
            set { ViewState["ConfirmTypeName"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.SubInspectId = Request.Params["SubInspectId"];
                this.ConfirmType = int.Parse(Request.Params["ConfirmType"]);
                if (this.ConfirmType == 1)
                {
                    this.ConfirmTypeName = "分包商";
                }
                if (this.ConfirmType == 2)
                {
                    this.ConfirmTypeName = "承包商";
                }
                if (this.ConfirmType == 3)
                {
                    this.ConfirmTypeName = "监理";
                }
                if (this.ConfirmType == 4)
                {
                    this.ConfirmTypeName = "业主";
                }
                this.BindGrid();
            }
        }
        #region 数据绑定
        /// 
        /// 绑定数据
        /// 
        public void BindGrid(int isPass = -1)
        {
            var db = Funs.DB;
            var term = db.PreRun_SubInspectTerm.FirstOrDefault(x => x.SubInspectId == this.SubInspectId);
            if (term != null)
            {
                lblIsUnifyWanderAbout.Text = term.IsUnifyWanderAbout == 1 ? "是" : "否";
                lblUnifyWanderAboutData.Text = term.UnifyWanderAboutData != null ? term.UnifyWanderAboutData.Value.ToString("yyyy-MM-dd") : string.Empty;
                unifyfile.Hidden = term.IsUnifyWanderAbout == 1 ? false : true;
            }
            //获取子系统
            var data = new List();
            //var list = Funs.DB.PreRun_SubInspectTermItem.Where(x => x.SubInspectId == this.SubInspectId).OrderBy(x => x.Sort).ToList();
            var list = (from x in db.PreRun_SubInspectTermItem
                        join y in db.Sys_User on x.InspectedUser equals y.UserId
                        where x.SubInspectId == this.SubInspectId
                        select new
                        {
                            x.TermItemId,
                            x.SubItemId,
                            x.SubInspectId,
                            x.WorkInspectName,
                            x.InspectionResults,
                            x.InspectionIllustrate,
                            x.SubcontractorIsPass,
                            x.SubcontractorRemark,
                            x.ContractorIsPass,
                            x.ContractorRemark,
                            x.SupervisionIsPass,
                            x.SupervisionRemark,
                            x.OwnerIsPass,
                            x.OwnerRemark,
                            x.Sort,
                            InspectedUserName = y.UserName
                        }
                        ).OrderBy(z => z.Sort).ToList();
            if (list.Count() > 0)
            {
                foreach (var item in list)
                {
                    var model = new ConfirmIsPass();
                    model.TermItemId = item.TermItemId;
                    model.SubItemId = item.SubItemId;
                    model.SubInspectId = item.SubInspectId;
                    model.WorkInspectName = item.WorkInspectName;
                    model.InspectedUserName = item.InspectedUserName;
                    model.InspectionResults = item.InspectionResults;
                    model.ConfirmType = this.ConfirmType;
                    model.InspectionIllustrate = item.InspectionIllustrate;
                    model.ConfirmTypeName = this.ConfirmTypeName;
                    //1=分包商2=承包商3=监理4=业主
                    if (this.ConfirmType == 1)
                    {
                        model.IsPass = isPass != -1 ? isPass : item.SubcontractorIsPass;
                        model.Remark = item.SubcontractorRemark;
                    }
                    if (this.ConfirmType == 2)
                    {
                        model.IsPass = isPass != -1 ? isPass : item.ContractorIsPass;
                        model.Remark = item.ContractorRemark;
                    }
                    if (this.ConfirmType == 3)
                    {
                        model.IsPass = isPass != -1 ? isPass : item.SupervisionIsPass;
                        model.Remark = item.SupervisionRemark;
                    }
                    if (this.ConfirmType == 4)
                    {
                        model.IsPass = isPass != -1 ? isPass : item.OwnerIsPass;
                        model.Remark = item.OwnerRemark;
                    }
                    data.Add(model);
                }
            }
            Grid1.DataSource = data;
            Grid1.DataBind();
            titleName.Title = this.ConfirmType == 1 ? "分包商确认签字" : this.ConfirmType == 2 ? "承包商确认签字" : this.ConfirmType == 3 ? "监理确认签字" : this.ConfirmType == 4 ? "业主确认签字" : "";
        }
        /// 
        /// 排序
        /// 
        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid();
        }
        /// 
        /// 检测结果
        /// 
        /// 
        public string Results(object value)
        {
            var result = string.Empty;
            if (value != null)
            {
                var intVal = int.Parse(value.ToString());
                if (intVal == 1)
                {
                    result = "通过";
                }
                else if (intVal == 0)
                {
                    result = "未通过";
                }
            }
            return result;
        }
        #endregion
        #region 按钮和事件
        /// 
        /// 保存
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                JArray mergedData = Grid1.GetMergedData();
                foreach (JObject mergedRow in mergedData)
                {
                    string status = mergedRow.Value("status");
                    JObject values = mergedRow.Value("values");
                    int i = mergedRow.Value("index");
                    GridRow row = Grid1.Rows[i];
                    System.Web.UI.WebControls.RadioButtonList rblIsPass = (System.Web.UI.WebControls.RadioButtonList)row.FindControl("rblIsPass");
                    var termItemId = this.Grid1.Rows[i].DataKeys[0].ToString();
                    //获取子系统信息
                    var model = Funs.DB.PreRun_SubInspectTermItem.FirstOrDefault(x => x.TermItemId == termItemId);
                    if (model != null)
                    {
                        if (!string.IsNullOrWhiteSpace(rblIsPass.SelectedValue))
                        {
                            //1=分包商2=承包商3=监理4=业主
                            if (this.ConfirmType == 1)
                            {
                                model.SubcontractorIsPass = int.Parse(rblIsPass.SelectedValue);
                                model.SubcontractorRemark = values.Value("Remark");
                            }
                            else if (this.ConfirmType == 2)
                            {
                                model.ContractorIsPass = int.Parse(rblIsPass.SelectedValue);
                                model.ContractorRemark = values.Value("Remark");
                            }
                            else if (this.ConfirmType == 3)
                            {
                                model.SupervisionIsPass = int.Parse(rblIsPass.SelectedValue);
                                model.SupervisionRemark = values.Value("Remark");
                            }
                            else if (this.ConfirmType == 4)
                            {
                                model.OwnerIsPass = int.Parse(rblIsPass.SelectedValue);
                                model.OwnerRemark = values.Value("Remark");
                            }
                        }
                        Funs.DB.SubmitChanges();
                    }
                }
                var subInspectId = this.Grid1.Rows[0].DataKeys[3].ToString();
                var subModel = Funs.DB.PreRun_SubInspectTerm.FirstOrDefault(x => x.SubInspectId == subInspectId);
                if (subModel != null)
                {
                    //1=分包商2=承包商3=监理4=业主
                    if (this.ConfirmType == 1)
                    {
                        if (Funs.DB.PreRun_SubInspectTermItem.Count(x => x.SubInspectId == subInspectId && x.SubcontractorIsPass.GetValueOrDefault() != 1) == 0)
                        {
                            subModel.SubcontractorIsAllPass = 1;
                            subModel.SubcontractorAllPassData = DateTime.Now;
                        }
                        else
                        {
                            subModel.SubcontractorIsAllPass = 0;
                            subModel.SubcontractorAllPassData = null;
                        }
                    }
                    else if (this.ConfirmType == 2)
                    {
                        if (Funs.DB.PreRun_SubInspectTermItem.Count(x => x.SubInspectId == subInspectId && x.ContractorIsPass.GetValueOrDefault() != 1) == 0)
                        {
                            subModel.ContractorIsAllPass = 1;
                            subModel.ContractorAllPassData = DateTime.Now;
                        }
                        else
                        {
                            subModel.ContractorIsAllPass = 0;
                            subModel.ContractorAllPassData = null;
                        }
                    }
                    else if (this.ConfirmType == 3)
                    {
                        if (Funs.DB.PreRun_SubInspectTermItem.Count(x => x.SubInspectId == subInspectId && x.SupervisionIsPass.GetValueOrDefault() != 1) == 0)
                        {
                            subModel.SupervisionIsAllPass = 1;
                            subModel.SupervisionAllPassData = DateTime.Now;
                        }
                        else
                        {
                            subModel.SupervisionIsAllPass = 0;
                            subModel.SupervisionAllPassData = null;
                        }
                    }
                    else if (this.ConfirmType == 4)
                    {
                        if (Funs.DB.PreRun_SubInspectTermItem.Count(x => x.SubInspectId == subInspectId && x.OwnerIsPass.GetValueOrDefault() != 1) == 0)
                        {
                            subModel.OwnerIsAllPass = 1;
                            subModel.OwnerAllPassData = DateTime.Now;
                        }
                        else
                        {
                            subModel.OwnerIsAllPass = 0;
                            subModel.OwnerAllPassData = null;
                        }
                    }
                    //判断是否全部通过
                    if (subModel.SubcontractorIsAllPass == 1 && subModel.ContractorIsAllPass == 1 && subModel.SupervisionIsAllPass == 1 && subModel.OwnerIsAllPass == 1)
                    {
                        subModel.WanderIsComplete = 1;
                        subModel.WanderCompleteData = DateTime.Now;
                    }
                    else
                    {
                        subModel.WanderIsComplete = 0;
                        subModel.WanderCompleteData = null;
                    }
                }
                Funs.DB.SubmitChanges();
                BindGrid();
                ShowNotify("保存成功!");
            }
            catch (Exception ex)
            {
                ShowNotify(ex.Message, MessageBoxIcon.Error);
            }
        }
        ///// 
        ///// 窗口关闭
        ///// 
        //protected void Window1_Close(object sender, WindowCloseEventArgs e)
        //{
        //    BindGrid();
        //}
        /// 
        /// 导出
        /// 
        protected void btnExport_Click(object sender, EventArgs e)
        {
            string rootPath = Server.MapPath("~/") + Const.ExcelUrl;
            //导出文件
            string filePath = rootPath + DateTime.Now.ToString("yyyyMMddhhmmss") + "\\";
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            string ReportFileName = filePath + this.ConfirmTypeName + "确认签字.xlsx";
            //获取工作包检查表
            var termData = from a in Funs.DB.PreRun_SubInspectTerm
                           join b in Funs.DB.Base_Project on a.ProjectId equals b.ProjectId
                           join c in Funs.DB.PreRun_WorkPackage on a.WorkPackId equals c.WorkPackId
                           join zz in Funs.DB.PreRun_SysDevice on a.InstallationId equals zz.PreRunId//装置
                           join gx in Funs.DB.PreRun_SysDevice on a.ProcessesId equals gx.PreRunId//工序
                           join xt in Funs.DB.PreRun_SysDevice on a.SystemId equals xt.PreRunId//系统
                           select new { a.SubInspectId, a.ProjectId, b.ProjectName, b.ShortName, b.ProjectCode, a.InstallationId, a.ProcessesId, a.SystemId, a.SubSystemId, a.WorkPackId, a.InspectResult, a.Subcontractor, a.Contractor, a.Supervision, a.Owner, a.InspectionIsAllPass, a.SubcontractorIsAllPass, a.ContractorIsAllPass, a.SupervisionIsAllPass, a.OwnerIsAllPass, a.WorkPackType, a.PropertyTechnologyId, a.InspectTime, a.AddUser, a.AddTime, c.WorkPackName, zzName = zz.PreRunName, gxName = gx.PreRunName, xtName = xt.PreRunName };
            if (termData != null)
            {
                var termModel = termData.FirstOrDefault();
                //获取工作包检查项表
                var termItems = Funs.DB.PreRun_SubInspectTermItem.Where(x => x.SubInspectId == this.SubInspectId).OrderBy(x => x.Sort).ToList();
                //获取管道或者设备号
                var termCodes = string.Empty;
                //1=管道2=设备
                var ids = termModel.PropertyTechnologyId.Split(',').ToList();
                if (termModel.WorkPackType == 1)
                {
                    var codeDatas = Funs.DB.PreRun_PropertySysPiping.Where(x => ids.Contains(x.PropertyId)).ToList();
                    if (codeDatas.Count > 0)
                    {
                        termCodes = string.Join(",", codeDatas.ConvertAll(x => x.PipingCode));
                    }
                }
                else
                {
                    var codeDatas = Funs.DB.PreRun_TechnologySysPiping.Where(x => ids.Contains(x.TechnologyId)).ToList();
                    if (codeDatas.Count > 0)
                    {
                        termCodes = string.Join(",", codeDatas.ConvertAll(x => x.TagNumber));
                    }
                }
                int rowIndex = 0;
                XSSFWorkbook hssfworkbook = new XSSFWorkbook();
                XSSFSheet ws = (XSSFSheet)hssfworkbook.CreateSheet(this.ConfirmTypeName + "确认签字");
                #region 列宽
                ws.SetColumnWidth(0, (7 * 256));
                ws.SetColumnWidth(1, (4 * 256));
                ws.SetColumnWidth(2, (4 * 256));
                ws.SetColumnWidth(3, (4 * 256));
                ws.SetColumnWidth(4, (10 * 256));
                ws.SetColumnWidth(5, (10 * 256));
                ws.SetColumnWidth(6, (10 * 256));
                ws.SetColumnWidth(7, (10 * 256));
                ws.SetColumnWidth(8, (3 * 256));
                ws.SetColumnWidth(9, (3 * 256));
                ws.SetColumnWidth(10, (3 * 256));
                ws.SetColumnWidth(11, (3 * 256));
                ws.SetColumnWidth(12, (3 * 256));
                ws.SetColumnWidth(13, (3 * 256));
                ws.SetColumnWidth(14, (3 * 256));
                ws.SetColumnWidth(15, (3 * 256));
                ws.SetColumnWidth(16, (3 * 256));
                ws.SetColumnWidth(17, (3 * 256));
                #endregion
                #region 样式
                //头部样式居中
                ICellStyle titleStyle = SetExcelStyle(hssfworkbook, BorderStyle.Thin, BorderStyle.Thin, BorderStyle.Thin, BorderStyle.Thin, VerticalAlignment.Center, HorizontalAlignment.Center, 14, true, true);
                //头部样式靠左
                ICellStyle leftTitleStyle = SetExcelStyle(hssfworkbook, BorderStyle.Thin, BorderStyle.Thin, BorderStyle.Thin, BorderStyle.Thin, VerticalAlignment.Center, HorizontalAlignment.Left, 14, true, true);
                //公共样式
                ICellStyle style = SetExcelStyle(hssfworkbook, BorderStyle.Thin, BorderStyle.Thin, BorderStyle.Thin, BorderStyle.Thin, VerticalAlignment.Center, HorizontalAlignment.Center, 10.5, true);
                //公共样式靠左
                ICellStyle leftStyle = SetExcelStyle(hssfworkbook, BorderStyle.Thin, BorderStyle.Thin, BorderStyle.Thin, BorderStyle.Thin, VerticalAlignment.Center, HorizontalAlignment.Left, 10.5, true);
                //公共样式靠左上对其
                ICellStyle leftTopStyle = SetExcelStyle(hssfworkbook, BorderStyle.Thin, BorderStyle.Thin, BorderStyle.Thin, BorderStyle.Thin, VerticalAlignment.Top, HorizontalAlignment.Left, 10.5, true);
                //公共样式加粗
                ICellStyle styleBold = SetExcelStyle(hssfworkbook, BorderStyle.Thin, BorderStyle.Thin, BorderStyle.Thin, BorderStyle.Thin, VerticalAlignment.Center, HorizontalAlignment.Center, 10.5, true, true);
                #endregion
                #region 头部
                ws = ExcelCreateRowTitle(ws, hssfworkbook, style, rowIndex, rowIndex + 5, 0, 17);
                //行1
                var region = new CellRangeAddress(rowIndex, rowIndex + 2, 0, 0);
                ws.AddMergedRegion(region);
                byte[] bytes = File.ReadAllBytes(Server.MapPath("~/") + "Images\\Template.png");
                int pictureIdx = hssfworkbook.AddPicture(bytes, PictureType.JPEG);
                IDrawing patriarch = ws.CreateDrawingPatriarch();
                IClientAnchor anchor = patriarch.CreateAnchor(0, 0, 0, 0, 0, rowIndex, 1, rowIndex + 2);
                IPicture pict = patriarch.CreatePicture(anchor, pictureIdx);
                //pict.Resize();
                region = new CellRangeAddress(rowIndex, rowIndex + 2, 1, 3);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex).GetCell(1).SetCellValue("中国五环工程有限公司");
                ws.GetRow(rowIndex).GetCell(1).CellStyle =
                ws.GetRow(rowIndex).GetCell(2).CellStyle =
                ws.GetRow(rowIndex).GetCell(3).CellStyle = leftTitleStyle;
                region = new CellRangeAddress(rowIndex, rowIndex, 4, 7);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex).GetCell(4).SetCellValue(termModel.ProjectName);
                ws.GetRow(rowIndex).GetCell(4).CellStyle = style;
                region = new CellRangeAddress(rowIndex, rowIndex, 8, 12);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex).GetCell(8).SetCellValue("项目号");
                ws.GetRow(rowIndex).GetCell(8).CellStyle = style;
                region = new CellRangeAddress(rowIndex, rowIndex, 13, 17);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex).GetCell(13).SetCellValue(termModel.ProjectCode);
                ws.GetRow(rowIndex).GetCell(13).CellStyle = style;
                region = new CellRangeAddress(rowIndex + 1, rowIndex + 1, 4, 7);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 1).GetCell(4).SetCellValue($"({termModel.zzName})({termModel.gxName}/{termModel.xtName})");
                ws.GetRow(rowIndex + 1).GetCell(4).CellStyle = style;
                region = new CellRangeAddress(rowIndex + 1, rowIndex + 1, 8, 12);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 1).GetCell(8).SetCellValue("(文件号)");
                ws.GetRow(rowIndex + 1).GetCell(8).CellStyle = style;
                region = new CellRangeAddress(rowIndex + 1, rowIndex + 1, 13, 17);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 1).GetCell(13).SetCellValue("");
                ws.GetRow(rowIndex + 1).GetCell(13).CellStyle = style;
                region = new CellRangeAddress(rowIndex + 2, rowIndex + 2, 4, 7);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 2).GetCell(4).SetCellValue($"{termModel.WorkPackName}条件检查表");
                ws.GetRow(rowIndex + 2).GetCell(4).CellStyle = titleStyle;
                region = new CellRangeAddress(rowIndex + 2, rowIndex + 2, 8, 12);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 2).GetCell(8).SetCellValue("第   1    页");
                ws.GetRow(rowIndex + 2).GetCell(8).CellStyle = style;
                region = new CellRangeAddress(rowIndex + 2, rowIndex + 2, 13, 17);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 2).GetCell(13).SetCellValue("共    1     页");
                ws.GetRow(rowIndex + 2).GetCell(13).CellStyle = style;
                //行4,行5
                region = new CellRangeAddress(rowIndex + 3, rowIndex + 4, 0, 2);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 3).GetCell(0).CellStyle = style;
                ws.GetRow(rowIndex + 3).GetCell(0).SetCellValue(termModel.WorkPackType == 1 ? "管道号" : "设备号");
                region = new CellRangeAddress(rowIndex + 3, rowIndex + 4, 3, 11);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 3).GetCell(3).CellStyle = leftStyle;
                ws.GetRow(rowIndex + 3).GetCell(3).SetCellValue(termCodes);
                region = new CellRangeAddress(rowIndex + 3, rowIndex + 3, 12, 17);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 3).GetCell(12).CellStyle = style;
                ws.GetRow(rowIndex + 3).GetCell(12).SetCellValue("检查日期");
                region = new CellRangeAddress(rowIndex + 4, rowIndex + 4, 12, 17);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 4).GetCell(12).CellStyle = style;
                ws.GetRow(rowIndex + 4).GetCell(12).SetCellValue(DateTime.Now.ToString("yyyy年MM月dd日"));
                //行6
                ws.GetRow(rowIndex + 5).GetCell(0).CellStyle = styleBold;
                ws.GetRow(rowIndex + 5).GetCell(0).SetCellValue("序号");
                region = new CellRangeAddress(rowIndex + 5, rowIndex + 5, 1, 7);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 5).GetCell(1).CellStyle = styleBold;
                ws.GetRow(rowIndex + 5).GetCell(1).SetCellValue("检查项目");
                region = new CellRangeAddress(rowIndex + 5, rowIndex + 5, 8, 12);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 5).GetCell(8).CellStyle = styleBold;
                ws.GetRow(rowIndex + 5).GetCell(8).SetCellValue("结果");
                region = new CellRangeAddress(rowIndex + 5, rowIndex + 5, 13, 17);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 5).GetCell(13).CellStyle = styleBold;
                ws.GetRow(rowIndex + 5).GetCell(13).SetCellValue("备注");
                #endregion
                #region 表格
                var start = rowIndex + 6;
                var end = rowIndex + 5 + termItems.Count;
                ws = ExcelCreateRowTitle(ws, hssfworkbook, style, start, end, 0, 17);
                //合并单元格
                for (int hb = start; hb <= end; hb++)
                {
                    region = new CellRangeAddress(hb, hb, 1, 7);
                    ws.AddMergedRegion(region);
                    region = new CellRangeAddress(hb, hb, 8, 12);
                    ws.AddMergedRegion(region);
                    region = new CellRangeAddress(hb, hb, 13, 17);
                    ws.AddMergedRegion(region);
                }
                //数据
                int num = 1;
                var dataIndex = 6;
                foreach (var item in termItems)
                {
                    //序号
                    ws.GetRow(dataIndex).GetCell(0).SetCellValue(num);
                    //检查项目
                    ws.GetRow(dataIndex).GetCell(1).SetCellValue(item.WorkInspectName);
                    ws.GetRow(dataIndex).GetCell(1).CellStyle = leftStyle;
                    //结果
                    ws.GetRow(dataIndex).GetCell(8).SetCellValue("");
                    //备注
                    ws.GetRow(dataIndex).GetCell(13).SetCellValue("");
                    dataIndex++;
                    num++;
                }
                rowIndex = start + termItems.Count;
                #endregion
                #region 尾部
                ws = ExcelCreateRowTitle(ws, hssfworkbook, style, rowIndex, rowIndex, 0, 17, 100);
                //行1
                ws.GetRow(rowIndex).GetCell(0).SetCellValue("结论");
                region = new CellRangeAddress(rowIndex, rowIndex, 1, 17);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex).GetCell(1).SetCellValue("是否同意进行冲洗吹扫(包括整改意见):");
                ws.GetRow(rowIndex).GetCell(1).CellStyle = leftTopStyle;
                //行2
                ws = ExcelCreateRowTitle(ws, hssfworkbook, style, rowIndex + 1, rowIndex + 1, 0, 17, 80);
                ws.GetRow(rowIndex + 1).GetCell(0).SetCellValue("检查人员");
                region = new CellRangeAddress(rowIndex + 1, rowIndex + 1, 1, 4);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 1).GetCell(1).SetCellValue("施工单位:");
                ws.GetRow(rowIndex + 1).GetCell(1).CellStyle = leftTopStyle;
                region = new CellRangeAddress(rowIndex + 1, rowIndex + 1, 5, 6);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 1).GetCell(5).SetCellValue("总承包商:");
                ws.GetRow(rowIndex + 1).GetCell(5).CellStyle = leftTopStyle;
                region = new CellRangeAddress(rowIndex + 1, rowIndex + 1, 7, 11);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 1).GetCell(7).SetCellValue("监理:");
                ws.GetRow(rowIndex + 1).GetCell(7).CellStyle = leftTopStyle;
                region = new CellRangeAddress(rowIndex + 1, rowIndex + 1, 12, 17);
                ws.AddMergedRegion(region);
                ws.GetRow(rowIndex + 1).GetCell(12).SetCellValue("业主:");
                ws.GetRow(rowIndex + 1).GetCell(12).CellStyle = leftTopStyle;
                #endregion
                ws.PrintSetup.Landscape = false;
                ws.PrintSetup.PaperSize = 9;
                ws.ForceFormulaRecalculation = true;
                using (FileStream filess = File.OpenWrite(ReportFileName))
                {
                    hssfworkbook.Write(filess);
                }
                FileInfo filet = new FileInfo(ReportFileName);
                Response.Clear();
                Response.Charset = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息,为"文件下载/另存为"对话框指定默认文件名
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(this.ConfirmTypeName + "确认签字.xlsx"));
                // 添加头信息,指定文件大小,让浏览器能够显示下载进度
                Response.AddHeader("Content-Length", filet.Length.ToString());
                // 指定返回的是一个不能被客户端读取的流,必须被下载
                Response.ContentType = "application/ms-excel";
                // 把文件流发送到客户端
                Response.WriteFile(filet.FullName);
                // 停止页面的执行
                Response.End();
            }
        }
        /// 
        /// 导入
        /// 
        protected void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.fileData.HasFile == false)
                {
                    ShowNotify("请选择excel文件!", MessageBoxIcon.Warning);
                    return;
                }
                string IsXls = Path.GetExtension(this.fileData.FileName).ToString().Trim().ToLower();
                if (IsXls != ".xls" && IsXls != ".xlsx")
                {
                    ShowNotify("excel文件类型错误!", MessageBoxIcon.Warning);
                    return;
                }
                string rootPath = Server.MapPath("~/");
                string initFullPath = rootPath + Const.ExcelUrl;
                if (!Directory.Exists(initFullPath))
                {
                    Directory.CreateDirectory(initFullPath);
                }
                //指定上传文件名称
                string fileUrl = BLL.Funs.GetNewFileName() + IsXls;
                //上传文件路径
                string filePath = initFullPath + fileUrl;
                //文件上传服务器
                this.fileData.PostedFile.SaveAs(filePath);
                //文件上传服务器后的名称
                string fileName = rootPath + Const.ExcelUrl + fileUrl;
                //读取Excel
                DataSet ds = NPOIHelper.ExcelToDataSet(fileName, out string message, false);
                if (ds == null)
                {
                    ShowNotify("模板错误,请从系统下载正确的模板!", MessageBoxIcon.Warning);
                    return;
                }
                if (!string.IsNullOrWhiteSpace(message))
                {
                    ShowNotify(message, MessageBoxIcon.Warning);
                    return;
                }
                if (ds.Tables[0].Rows.Count > 6)
                {
                    var fileVerify = VerifyFile(ds);
                    if (!fileVerify)
                    {
                        ShowNotify("请使用导出的Excel作为模板!", MessageBoxIcon.Warning);
                        return;
                    }
                    List list = new List();
                    //数据导入
                    for (int i = 6; i < ds.Tables[0].Rows.Count; i++)
                    {
                        if (string.IsNullOrWhiteSpace(ds.Tables[0].Rows[i][1].ToString())) continue;
                        if (string.IsNullOrWhiteSpace(ds.Tables[0].Rows[i][8].ToString())) continue;
                        var model = Funs.DB.PreRun_SubInspectTermItem.FirstOrDefault(x => x.WorkInspectName.Trim() == ds.Tables[0].Rows[i][1].ToString().Trim());
                        if (model == null) continue;
                        var resultStr = ds.Tables[0].Rows[i][8].ToString();
                        var remark = ds.Tables[0].Rows[i][13].ToString();
                        var isPass = 0;
                        if (resultStr.Trim() == "通过")
                        {
                            isPass = 1;
                        }
                        if (this.ConfirmType == 1)
                        {
                            model.SubcontractorIsPass = isPass;
                            if (!string.IsNullOrWhiteSpace(remark))
                            {
                                model.SubcontractorRemark = remark;
                            }
                        }
                        else if (this.ConfirmType == 2)
                        {
                            model.ContractorIsPass = isPass;
                            if (!string.IsNullOrWhiteSpace(remark))
                            {
                                model.ContractorRemark = remark;
                            }
                        }
                        else if (this.ConfirmType == 3)
                        {
                            model.SupervisionIsPass = isPass;
                            if (!string.IsNullOrWhiteSpace(remark))
                            {
                                model.SupervisionRemark = remark;
                            }
                        }
                        else if (this.ConfirmType == 4)
                        {
                            model.OwnerIsPass = isPass;
                            if (!string.IsNullOrWhiteSpace(remark))
                            {
                                model.OwnerRemark = remark;
                            }
                        }
                        Funs.DB.SubmitChanges();
                    }
                }
                else
                {
                    ShowNotify("文件无数据!", MessageBoxIcon.Warning);
                }
                var subModel = Funs.DB.PreRun_SubInspectTerm.FirstOrDefault(x => x.SubInspectId == this.SubInspectId);
                if (subModel != null)
                {
                    //1=分包商2=承包商3=监理4=业主
                    if (this.ConfirmType == 1)
                    {
                        if (Funs.DB.PreRun_SubInspectTermItem.Count(x => x.SubInspectId == this.SubInspectId && x.SubcontractorIsPass.GetValueOrDefault() != 1) == 0)
                        {
                            subModel.SubcontractorIsAllPass = 1;
                        }
                        else
                        {
                            subModel.SubcontractorIsAllPass = 0;
                        }
                    }
                    else if (this.ConfirmType == 2)
                    {
                        if (Funs.DB.PreRun_SubInspectTermItem.Count(x => x.SubInspectId == this.SubInspectId && x.ContractorIsPass.GetValueOrDefault() != 1) == 0)
                        {
                            subModel.ContractorIsAllPass = 1;
                        }
                        else
                        {
                            subModel.ContractorIsAllPass = 0;
                        }
                    }
                    else if (this.ConfirmType == 3)
                    {
                        if (Funs.DB.PreRun_SubInspectTermItem.Count(x => x.SubInspectId == this.SubInspectId && x.SupervisionIsPass.GetValueOrDefault() != 1) == 0)
                        {
                            subModel.SupervisionIsAllPass = 1;
                        }
                        else
                        {
                            subModel.SupervisionIsAllPass = 0;
                        }
                    }
                    else if (this.ConfirmType == 4)
                    {
                        if (Funs.DB.PreRun_SubInspectTermItem.Count(x => x.SubInspectId == this.SubInspectId && x.OwnerIsPass.GetValueOrDefault() != 1) == 0)
                        {
                            subModel.OwnerIsAllPass = 1;
                        }
                        else
                        {
                            subModel.OwnerIsAllPass = 0;
                        }
                    }
                    Funs.DB.SubmitChanges();
                }
                BindGrid();
                fileData.Reset();
                ShowNotify("导入成功!", MessageBoxIcon.Success);
            }
            catch (Exception ex)
            {
                ShowNotify(ex.Message, MessageBoxIcon.Warning);
            }
        }
        /// 
        /// 行加载事件
        /// 
        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            System.Web.UI.WebControls.RadioButtonList rblIsPass = (System.Web.UI.WebControls.RadioButtonList)Grid1.Rows[e.RowIndex].FindControl("rblIsPass");
            int isPass = 1;
            if (Grid1.DataKeys[e.RowIndex][4] != null) isPass = int.Parse(Grid1.DataKeys[e.RowIndex][4].ToString());
            rblIsPass.SelectedValue = isPass.ToString();
            if (rblIsPass.SelectedValue != "1")
            {
                rblIsAllPass.SelectedValue = "0";
            }
        }
        /// 
        /// 实体绑定
        /// 
        public class ConfirmIsPass
        {
            /// 
            /// 主键
            /// 
            public string TermItemId { get; set; }
            /// 
            /// 检查项主键
            /// 
            public string SubItemId { get; set; }
            /// 
            /// 检查表主键
            /// 
            public string SubInspectId { get; set; }
            /// 
            /// 名称
            /// 
            public string WorkInspectName { get; set; }
            /// 
            /// 检查说明
            /// 
            public string InspectionIllustrate { get; set; }
            /// 
            /// 确认类型1=分包商2=承包商3=监理4=业主
            /// 
            public int ConfirmType { get; set; }
            /// 
            /// 确认类型名称
            /// 
            public string ConfirmTypeName { get; set; }
            public string InspectedUserName { get; set; }
            public int? InspectionResults { get; set; }
            /// 
            /// 是否通过
            /// 
            public int? IsPass { get; set; }
            /// 
            /// 备注
            /// 
            public string Remark { get; set; }
        }
        /// 
        /// 检查项确认事件
        /// 
        protected void rblIsPass_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < Grid1.Rows.Count; i++)
            {
                System.Web.UI.WebControls.RadioButtonList rblIsPass = (System.Web.UI.WebControls.RadioButtonList)Grid1.Rows[i].FindControl("rblIsPass");
                if (rblIsPass.SelectedValue != "1")
                {
                    rblIsAllPass.SelectedValue = "0";
                }
            }
        }
        /// 
        /// 是否同意进行预试车活动事件
        /// 
        protected void rblIsAllPass_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGrid(int.Parse(rblIsAllPass.SelectedValue));
        }
        /// 
        /// 附件上传
        /// 
        protected void btnAttach_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../../AttachFile/webuploader.aspx?type=0&toKeyId={0}&path=FileUpload/CheckControl&menuId={1}", $"{this.SubInspectId}_{this.ConfirmType}", Const.TestRunMenuId)));
        }
        /// 
        /// 统一流转通过附件查看
        /// 
        protected void btnUnifyUpload_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(WindowAtt.GetShowReference(String.Format("../../AttachFile/webuploader.aspx?type=-1&toKeyId={0}&path=FileUpload/CheckControl&menuId={1}", this.SubInspectId + "_unify", Const.TestRunMenuId)));
        }
        #endregion
        #region 私有方法
        private bool VerifyFile(DataSet ds)
        {
            var result = true;
            if (ds.Tables[0].Rows[5][0].ToString() != "序号") result = false;
            if (ds.Tables[0].Rows[5][1].ToString() != "检查项目") result = false;
            if (ds.Tables[0].Rows[5][8].ToString() != "结果") result = false;
            if (ds.Tables[0].Rows[5][13].ToString() != "备注") result = false;
            return result;
        }
        /// 
        /// 获取某一列的所有值
        /// 
        /// 列数据类型
        /// 数据表
        /// 列名
        /// 
        public static List GetColumnValues(DataTable dtSource, string filedName)
        {
            return (from r in dtSource.AsEnumerable() select r.Field(filedName)).ToList();
        }
        /// 
        /// 验证datatable某列是否存在重复
        /// 
        /// 
        public bool HasRepeatData(DataTable dt, string[] colName)
        {
            bool flag = false;
            DataView myDataView = new DataView(dt);
            if (myDataView.ToTable(true, colName).Rows.Count < dt.Rows.Count)
            {
                flag = true;
            }
            return flag;
        }
        /// 
        /// 创建样式
        /// 
        /// 
        public static ICellStyle SetExcelStyle(XSSFWorkbook wb, BorderStyle Bottom, BorderStyle Left, BorderStyle Right, BorderStyle Top, VerticalAlignment VerAig, HorizontalAlignment HorAig, double FontSize, bool WrapText = true, bool Bold = false, string FontName = "宋体")
        {
            ICellStyle style = wb.CreateCellStyle();
            style.BorderBottom = Bottom;
            style.BorderLeft = Left;
            style.BorderRight = Right;
            style.BorderTop = Top;
            style.VerticalAlignment = VerAig;
            style.Alignment = HorAig;
            IFont font = wb.CreateFont();
            font.FontHeightInPoints = FontSize;
            font.IsBold = Bold;
            font.FontName = FontName;
            style.SetFont(font);
            style.WrapText = WrapText;
            return style;
        }
        /// 
        /// 创建头部
        /// 
        /// 
        private XSSFSheet ExcelCreateRowTitle(XSSFSheet ws, XSSFWorkbook hssfworkbook, ICellStyle style, int sRows, int eRows, int cStart, int cEnd, float height = 21)
        {
            for (int i = sRows; i <= eRows; i++)
            {
                ws.CreateRow(i);
                ws.GetRow(i).HeightInPoints = height;
                for (int j = cStart; j <= cEnd; j++)
                {
                    ws.GetRow(i).CreateCell(j);
                    ws.GetRow(i).CreateCell(j).CellStyle = style;
                }
            }
            return ws;
        }
        #endregion
    }
}