using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using BLL;
using Model;
using AspNet = System.Web.UI.WebControls;
namespace FineUIPro.Web.ZHGL.InspectionSummary
{
    public partial class InspectionSummary : PageBase
    {
        /// 
        /// 页面加载
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
            }
        }
        /// 
        /// 加载表头
        /// 
        protected void Page_Init(object sender, EventArgs e)
        {
            InitGrid();
        }
        #region 加载表头
        private void InitGrid()
        {
            //根据在建项目获取表头
            var list = Funs.DB.Base_Project.Where(x => x.ProjectState == Const.ProjectState_1 || x.ProjectState == null).OrderBy(x => x.ProjectCode).ToList();
            for (int i = 0; i < list.Count; i++)
            {
                GroupField p = new GroupField();
                p.Width = Unit.Pixel(200);
                p.HeaderText = list[i].ShortName;
                p.TextAlign = TextAlign.Left;
                //p.HeaderToolTip= list[i].
                BoundField person = new BoundField();
                person.Width = Unit.Pixel(200);
                person.DataField = "ThisProject" + (i + 1).ToString();
                #region 加载施工、安全、质量经理
                var textJl = "";
                var getPUser = Funs.DB.Project_ProjectUser.Where(x => x.ProjectId == list[i].ProjectId);
                var getSysUser = Funs.DB.Sys_User;
                if (getPUser.Count() > 0)
                {
                    ///施工经理 
                    var c = getPUser.FirstOrDefault(x => x.RoleId.Contains(BLL.Const.ConstructionManager));
                    if (c != null)
                    {
                        textJl += getSysUser.Where(x => x.UserId == c.UserId).FirstOrDefault().UserName + ",";
                    }
                    ////安全经理
                    var h = getPUser.FirstOrDefault(x => x.RoleId.Contains(BLL.Const.HSSEManager));
                    if (h != null)
                    {
                        textJl += getSysUser.Where(x => x.UserId == h.UserId).FirstOrDefault().UserName + ",";
                    }
                    ////质量经理
                    var qa = getPUser.FirstOrDefault(x => x.RoleId.Contains(BLL.Const.QAManager));
                    if (qa != null)
                    {
                        textJl += getSysUser.Where(x => x.UserId == qa.UserId).FirstOrDefault().UserName;
                    }
                }
                #endregion
                person.HeaderText = textJl;
                person.DataToolTipField = "CompileDate" + (i + 1).ToString();
                person.ColumnID = "ThisProject" + (i + 1).ToString();
                
                p.Columns.Add(person);
                
                Grid1.Columns.Add(p);
            }
        }
        #endregion
        /// 
        /// 判断生成操作
        /// 
        protected void btnNew_Juge(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.drpCompileDateMonth.Text.Trim()))
            {
                ShowNotify("日期不能为空。", MessageBoxIcon.Warning);
                PageContext.RegisterStartupScript("CloseRefresh()");
                return;
            }
            //根据日期查询是否有数据
            var modelSum = Funs.DB.Inspection_Summary.Where(x => x.CompileDateMonth == this.drpCompileDateMonth.Text.Trim()).FirstOrDefault();
            //查到数据,二次确认
            if (modelSum != null)
            {
                PageContext.RegisterStartupScript(Confirm.GetShowReference("该日期已生成数据,是否确认重新生成?", String.Empty, MessageBoxIcon.Question,
                    PageManager1.GetCustomEventReference(false, "Confirmgd_OK"), PageManager1.GetCustomEventReference("Confirm_Cancel")));
                PageContext.RegisterStartupScript("CloseRefresh()");
            }
            else
            {
                btnNew_Click();
            }
        }
        /// 
        /// 确认按钮
        /// 
        /// 
        /// 
        protected void PageManager1_CustomEvent(object sender, CustomEventArgs e)
        {
            if (e.EventArgument == "Confirmgd_OK" || e.EventArgument == "Confirmgy_OK")
            {
                // 根据日期查询是否有数据
                var modelSum = Funs.DB.Inspection_Summary.Where(x => x.CompileDateMonth == this.drpCompileDateMonth.Text.Trim()).FirstOrDefault();
                //删除数据
                InspectionSummaryService.Delete(modelSum.CompileDateMonth);
                BindGrid();
                btnNew_Click();
            }
        }
        public class ProjectIdAndDate {
            public string ProjectId { get; set; }
            public DateTime? Mdate { get; set; }
            public string state { get; set; }
        }
        #region 生成按钮
        protected void btnNew_Click()
        {
            if (string.IsNullOrEmpty(this.drpCompileDateMonth.Text.Trim()))
            {
                ShowNotify("日期不能为空。", MessageBoxIcon.Warning);
                PageContext.RegisterStartupScript("CloseRefresh()");
                return;
            }
            List allList = new List();
            #region 生成操作
            //1.获取项目
            var SummeryResult = "0";
            #region 先一步查询各个表的数据
            var getPersonLists = (from x in Funs.DB.View_SitePerson_Person
                                  select new
                                  {
                                      x.ProjectId
                                  }).ToList();
            //特种作业人员
            var tzPersonList = (from x in Funs.DB.SitePerson_Person
                                join y in Funs.DB.Base_WorkPost on x.WorkPostId equals y.WorkPostId
                                where y.PostType == Const.PostType_2 && x.OutTime == null
                                select new { x.ProjectId, y.PostType }).ToList();
            //移动端安全巡检
            var list2 = Funs.DB.View_Hazard_HazardRegister.Select(x => new View_Hazard_HazardRegister
            {
                ProblemTypes = x.ProblemTypes,
                ProjectId = x.ProjectId,
                CheckTime = x.CheckTime,
                States = x.States
            }).Where(x => x.ProblemTypes == "1").ToList();
            //周例会
            var list3 = Funs.DB.Meeting_WeekMeeting.Select(x => new ProjectIdAndDate { ProjectId = x.ProjectId, Mdate = x.WeekMeetingDate }).ToList();
            //月例会
            //var list4 = Funs.DB.Meeting_MonthMeeting.Select(x => new ProjectIdAndDate { ProjectId = x.ProjectId, Mdate = x.MonthMeetingDate }).ToList();
            //安全领导小组会议
            var list4 = Funs.DB.Meeting_SafetyLeaderGroupMeeting.Select(x => new ProjectIdAndDate { ProjectId = x.ProjectId, Mdate = x.SafetyLeaderGroupMeetingDate }).ToList();
            //作业票
            var list5 = Funs.DB.View_License_LicenseManager
                .Select(x => new ProjectIdAndDate { ProjectId = x.ProjectId, Mdate = x.CompileDate })
                .ToList();
            //工程师日志
            var list6 = (from x in Funs.DB.Manager_HSSELog
                         where x.IsVisible != false
                         select new
                         {
                             x.ProjectId,
                             x.CompileDate,
                             x.IsVisible
                         }).ToList();
            //HSE管理月报
            var list7 = Funs.DB.Manager_MonthReportC.Select(x => new ProjectIdAndDate { ProjectId = x.ProjectId, Mdate = x.Months }).ToList();
            //质量巡检
            var list8 = Funs.DB.Check_CheckControl.Select(x => new ProjectIdAndDate { ProjectId = x.ProjectId, Mdate = x.CheckDate, state = x.State }).ToList();
            //设备材料报验
            var list10 = Funs.DB.Comprehensive_InspectionEquipment.Select
                (x => new ProjectIdAndDate { ProjectId = x.ProjectId, Mdate = x.InspectionDate }).ToList();
            //人员报验
            var list11 = Funs.DB.Comprehensive_InspectionPerson.
                Select(x => new ProjectIdAndDate { ProjectId = x.ProjectId, Mdate = x.ApprovalTime }).ToList();
            //机具报验
            var list13 = Funs.DB.Comprehensive_InspectionMachine
                .Select(x => new ProjectIdAndDate { ProjectId = x.ProjectId, Mdate = x.InspectionDate }).ToList();
            //设计变更管理
            var list14 = Funs.DB.Comprehensive_DesignChangeOrder
                .Select(x => new ProjectIdAndDate { ProjectId = x.ProjectId, Mdate = x.IssuedDate }).ToList();
            //施工方案管理
            var list15 = Funs.DB.Comprehensive_GeneralPlanApproval
                .Select(x => new ProjectIdAndDate { ProjectId = x.ProjectId, Mdate = x.ApprovalDate }).ToList();
            //超过一定规模的危大施工方案
            var list15_2 = Funs.DB.Comprehensive_MajorPlanApproval
                .Select(x => new ProjectIdAndDate { ProjectId = x.ProjectId, Mdate = x.ApprovalDate }).ToList();
            //设计交底管理
            var list16 = Funs.DB.Comprehensive_DesignDetails
                .Select(x=>new ProjectIdAndDate { ProjectId=x.ProjectId, Mdate = x.DetailsDate }).ToList();
            //NCR
            var list17 = Funs.DB.Comprehensive_NCRManagement
                .Select(x=>new ProjectIdAndDate { ProjectId=x.ProjectId, Mdate = x.IssuedDate }).ToList();
            //质量周报
            var list18 = (from x in Funs.DB.Report_WeekAndMonthReport
                          where x.ReportType=="1"
                          select new
                          {
                              x.ProjectId,
                              x.EndDate,
                              x.ReportType
                          }).ToList();
            //质量周报(新)
            var list18_2 = (from x in Funs.DB.Report_WeekAndMonthReport_New
                            where x.ReportType == "2"
                            select new
                            {
                                x.ProjectId,
                                x.EndDate,
                                x.ReportType
                            }).ToList();
            //质量月报
            var list19 = (from x in Funs.DB.Report_WeekAndMonthReport
                          where x.ReportType == "2"
                          select new
                          {
                              x.ProjectId,
                              x.EndDate,
                              x.ReportType
                          }).ToList();
            //质量月报(新)
            var list19_2 = (from x in Funs.DB.Report_WeekAndMonthReport_New
                            where x.ReportType == "1"
                            select new
                            {
                                x.ProjectId,
                                x.EndDate,
                                x.ReportType
                            }).ToList();
            //一次共检合格数
            var list20 = (from x in Funs.DB.ProcessControl_InspectionManagement 
                          where x.IsOnceQualified == true 
                          select new {  x.ProjectId,x.InspectionDate,x.IsOnceQualified,x.InspectionId, Isid= x.InspectionId }).ToList();
            ////总数
            var list21 = (from x in Funs.DB.ProcessControl_InspectionManagement
                          select new {  x.ProjectId, x.InspectionId, Isid = x.InspectionId,x.InspectionDate }).ToList();
            //关键事项
            var list22 = (from x in Funs.DB.GJSX
                          select new
                          {
                              x.ProjectId,
                              x.CreateDate
                          }).ToList();
            //人脸考勤
            //var list23 = (from x in Funs.DB.T_d_facerecord
            //              select new { x.ProjectId }).ToList();
            //实名制是否启用
            var list24 = (from x in Funs.DB.RealName_SynchroSet
                          join y in Funs.DB.Base_Project on x.ProCode equals y.ProjectCode
                          select new { y.ProjectId }).ToList();
            #endregion
            List listProjectid = new List();
            var list = (from x in Funs.DB.Base_Project
                        where x.ProjectState == Const.ProjectState_1 || x.ProjectState == null
                        orderby x.ProjectCode
                        select new
                        {
                            x.ProjectId,
                            x.ProjectState,
                            x.ProjectCode
                        }).ToList();
            //查询所有的projectid数据
            for (int i = 0; i < list.Count; i++)
            {
                listProjectid.Add(list[i].ProjectId);
            }
            //wbs数据查询
            var listWbs = Funs.DB.WBS_BreakdownProject.Select(x => new { ProjectId = x.ProjectId }).ToList();
            using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
            {
                for (int i = 0; i < list.Count; i++)
                {
                    var pid = list[i].ProjectId;
                    #region 安全模块
                    Inspection_Summary model = new Inspection_Summary();
                    model.ProjectId = pid;
                    //显示日期
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    //人员信息档案
                    model.InspectionSummaryMbId = "1";
                    model.SummeryResult = getPersonLists.Where(x => x.ProjectId == pid).ToList().Count().ToString();
                    allList.Add(model);
                    //特种作业人员
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "2";
                    model.SummeryResult = tzPersonList.Where(x=>x.ProjectId==pid).Count().ToString();
                    allList.Add(model);
                    //安全巡检
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "3";
                    var AqxjCount = list2.Where(x => x.ProjectId == pid).ToList().Count();
                    model.SummeryResult = AqxjCount.ToString();
                    //时间
                    if (AqxjCount > 0)
                    {
                        model.CompileDate = list2.Where(x => x.ProjectId == pid).OrderByDescending(x=>x.CheckTime).FirstOrDefault().CheckTime;
                    }
                    
                    allList.Add(model);
                    //安全巡检已闭合
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "28";
                    AqxjCount = list2.Where(x => x.ProjectId == pid && x.States=="3").ToList().Count();
                    model.SummeryResult = AqxjCount.ToString();
                    //时间
                    if (AqxjCount > 0)
                    {
                        model.CompileDate = list2.Where(x => x.ProjectId == pid).OrderByDescending(x => x.CheckTime).FirstOrDefault().CheckTime;
                    }
                    allList.Add(model);
                    //周例会
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDate = DateTime.Now;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "4";
                    var ZlhCount = list3.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = ZlhCount.ToString();
                    if (ZlhCount > 0)
                    {
                        //会议时间
                        model.CompileDate = list3.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    }
                    allList.Add(model);
                    //安全领导小组会议
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "5";
                    var YlhCount = list4.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = YlhCount.ToString();
                    if (YlhCount > 0)
                    {
                        //会议时间
                        model.CompileDate = list4.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate; 
                    }
                    
                    allList.Add(model);
                    //作业票
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "6";
                    var ZypCount = list5.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = ZypCount.ToString();
                    if (ZypCount>0)
                    {
                        //申请时间
                        model.CompileDate = list5.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    }
                    allList.Add(model);
                    
                    //工作报告
                    //工程师日志
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "7";
                    var GcsrzCount = list6.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = GcsrzCount.ToString();
                    if (GcsrzCount>0)
                    {
                        //日志时间
                        model.CompileDate = list6.Where(x => x.ProjectId == pid).OrderByDescending(x => x.CompileDate).FirstOrDefault().CompileDate;
                    }
                    allList.Add(model);
                    //HSE管理月报
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "8";
                    var HsseGlybCount = list7.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = HsseGlybCount.ToString();
                    if (HsseGlybCount>0)
                    {
                        var date = Convert.ToDateTime(list7.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().
                            Mdate);
                        date = date.AddDays(24);
                        //月份(显示25号)
                        model.CompileDate = date;
                    }
                    allList.Add(model);
                    #endregion
                    #region 质量模块
                    //质量巡检
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDate = DateTime.Now;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "9";
                    var ZlxjCount = list8.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = ZlxjCount.ToString();
                    if (ZlxjCount>0)
                    {
                        //巡检日期
                        model.CompileDate = list8.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate; 
                    }
                    allList.Add(model);
                    //质量巡检已闭合项
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDate = DateTime.Now;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "29";
                    //已闭合
                    ZlxjCount = list8.Where(x => x.ProjectId == pid&&x.state=="7").ToList().Count;
                    model.SummeryResult = ZlxjCount.ToString();
                    if (ZlxjCount > 0)
                    {
                        //巡检日期
                        model.CompileDate = list8.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    }
                    allList.Add(model);
                    //WBS数据
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "10";
                    var WbsCount = listWbs.Where(x => x.ProjectId == pid).ToList().Count;
                    if (WbsCount > 0)
                    {
                        model.SummeryResult = "已裁剪";
                    }
                    else {
                        model.SummeryResult = "未裁剪";
                    }
                    allList.Add(model);
                    //综合管理
                    //设备材料报验
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "11";
                    var SbclByCount = list10.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = SbclByCount.ToString();
                    if (SbclByCount>0)
                    {
                        //报验日期
                        model.CompileDate = list10.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    }
                    allList.Add(model);
                    //人员报验
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "12";
                    var RybyCount = list11.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = RybyCount.ToString();
                    if (RybyCount>0)
                    {
                        //批准日期
                        model.CompileDate = list11.Where(x => x.ProjectId == pid && x.Mdate != null).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    }
                    
                    allList.Add(model);
                    //机具报验
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "13";
                    var JjbyCount = list13.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = JjbyCount.ToString();
                    if (JjbyCount>0)
                    {
                        //报验日期
                        model.CompileDate = list13.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    }
                    allList.Add(model);
                    //设计变更单管理
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "14";
                    var SjdbgCount = list14.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = SjdbgCount.ToString();
                    if (SjdbgCount>0)
                    {
                        //下发日期
                        model.CompileDate = list14.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    }
                    allList.Add(model);
                    //施工方案管理
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "15";
                    var SgfaCount = list15.Where(x => x.ProjectId == pid).ToList().Count;
                    var bigCount = list15_2.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = (SgfaCount + bigCount).ToString();
                    DateTime? date1 = Convert.ToDateTime("1900-01-01");
                    DateTime? date2 = Convert.ToDateTime("1900-01-01");
                    if (SgfaCount > 0)
                    {
                        date1 = list15.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    }
                    if (bigCount > 0)
                    {
                        date2 = list15_2.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    }
                    if (SgfaCount > bigCount)
                    {
                        model.CompileDate = date1;
                    }
                    else
                    {
                        model.CompileDate = date2;
                    }
                    //if (bigCount > 0 && SgfaCount == 0)
                    //{
                    //    //审批日期
                    //    model.CompileDate = list15_2.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    //}
                    //else if (SgfaCount > 0)
                    //{
                    //    model.CompileDate = list15.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    //}
                    allList.Add(model);
                    //设计交底管理
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "16";
                    var SjjdCount = list16.Where(x => x.ProjectId == pid).ToList().Count; 
                    model.SummeryResult = SjjdCount.ToString();
                    if (SjjdCount>0)
                    {
                        //交底日期
                        model.CompileDate = list16.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    }
                    allList.Add(model);
                    //NCR
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "17";
                    var NcrCount = list17.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = NcrCount.ToString();
                    if (NcrCount>0)
                    {
                        //下发日期
                        model.CompileDate = list17.Where(x => x.ProjectId == pid).OrderByDescending(x => x.Mdate).FirstOrDefault().Mdate;
                    }
                    allList.Add(model);
                    //质量报表管理
                    //质量周报
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "18";
                    var SgzbCount = list18.Where(x => x.ProjectId == pid).ToList().Count;
                    var newSgzbCount = list18_2.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = (SgzbCount + newSgzbCount).ToString();
                    DateTime? weekDate1 = Convert.ToDateTime("1900-01-01");
                    DateTime? weekDate2 = Convert.ToDateTime("1900-01-01");
                    if(SgzbCount>0)
                    {
                        weekDate1= list18.Where(x => x.ProjectId == pid).OrderByDescending(x => x.EndDate).FirstOrDefault().EndDate;
                    }
                    if (newSgzbCount > 0)
                    {
                        weekDate2 = list18_2.Where(x => x.ProjectId == pid).OrderByDescending(x => x.EndDate).FirstOrDefault().EndDate;
                    }
                    if (weekDate1 > weekDate2)
                    {
                        model.CompileDate = weekDate1;
                    }
                    else
                    {
                        model.CompileDate = weekDate2;
                    }
                    //if (SgzbCount == 0 && newSgzbCount > 0)
                    //{
                    //    model.CompileDate = list18_2.Where(x => x.ProjectId == pid).OrderByDescending(x => x.EndDate).FirstOrDefault().EndDate;
                    //}
                    //else if (SgzbCount > 0)
                    //{
                    //    model.CompileDate = list18.Where(x => x.ProjectId == pid).OrderByDescending(x => x.EndDate).FirstOrDefault().EndDate;
                    //}
                    allList.Add(model);
                    //质量月报
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "19";
                    var SgybCount = list19.Where(x => x.ProjectId == pid).ToList().Count;
                    var newSgybCount = list19_2.Where(x => x.ProjectId == pid).ToList().Count;
                    model.SummeryResult = (SgybCount+ newSgybCount).ToString();
                    //if (newSgybCount > 0 && SgybCount == 0)
                    //{
                    //    model.CompileDate = list19_2.Where(x => x.ProjectId == pid).OrderByDescending(x => x.EndDate).FirstOrDefault().EndDate;
                    //}
                    //else if (SgybCount > 0)
                    //{
                    //    model.CompileDate = list19.Where(x => x.ProjectId == pid).OrderByDescending(x => x.EndDate).FirstOrDefault().EndDate;
                    //}
                    DateTime? monthDate1 = Convert.ToDateTime("1900-01-01");
                    DateTime? monthDate2= Convert.ToDateTime("1900-01-01");
                    if (SgybCount > 0)
                    {
                        monthDate1 = list19.Where(x => x.ProjectId == pid).OrderByDescending(x => x.EndDate).FirstOrDefault().EndDate; 
                    }
                    if (newSgybCount > 0)
                    {
                        monthDate2 = list19_2.Where(x => x.ProjectId == pid).OrderByDescending(x => x.EndDate).FirstOrDefault().EndDate;
                    }
                    if (monthDate1 > monthDate2)
                    {
                        model.CompileDate = monthDate1;
                    }
                    else
                    {
                        model.CompileDate = monthDate2;
                    }
                    allList.Add(model);
                    //过程控制管理
                    //一次共检合格数
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "20";
                    var hgs = list20.Where(x=>x.ProjectId==pid).ToList().Count();
                    if (hgs>0)
                    {
                        //验收日期
                        model.CompileDate = list20.Where(x => x.ProjectId == pid).OrderByDescending(x => x.InspectionDate).FirstOrDefault().InspectionDate;
                    }
                    model.SummeryResult = hgs.ToString();
                    allList.Add(model);
                    //总数
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "21";
                    var zs = list21.Where(x => x.ProjectId == pid).ToList().Count();
                    model.SummeryResult = zs.ToString();
                    allList.Add(model);
                    //一次共检合格合格率
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "22";
                    if (zs > 0)
                    {
                        model.SummeryResult = String.Format("{0:N2}", 100 * hgs / zs) + "%";
                    }
                    else
                    {
                        model.SummeryResult = "0%";
                    }
                    allList.Add(model);
                    #endregion
                    #region 关键事项
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "23";
                    var GjsxCount = list22.Where(x => x.ProjectId == pid).ToList().Count();
                    model.SummeryResult = GjsxCount.ToString();
                    if (GjsxCount>0)
                    {
                        //提出日期
                        model.CompileDate = list22.Where(x => x.ProjectId == pid).OrderByDescending(x => x.CreateDate).FirstOrDefault().CreateDate;
                    }
                    allList.Add(model);
                    #endregion
                    #region 现场考勤(是否对接)
                    //人脸考勤
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "24";
                    var Rykq =db.T_d_facerecord.Where(x => x.ProjectId == pid).Select(x=>x.ID).FirstOrDefault();
                    if (Rykq !=0)
                    {
                        model.SummeryResult = "已对接";
                    }
                    else {
                        model.SummeryResult = "未对接";
                    }
                    
                    allList.Add(model);
                    //集团实名制对接
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "25";
                    var Smz = list24.Where(x => x.ProjectId == pid).ToList().Count;
                    if (Smz > 0)
                    {
                        model.SummeryResult = "已对接";
                    }
                    else
                    {
                        model.SummeryResult = "未对接";
                    }
                    allList.Add(model);
                    #endregion
                    #region 视频监控(是否对接)
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "26";
                    model.SummeryResult = "";
                    allList.Add(model);
                    #endregion
                    #region 项目看板(暂时不弄)
                    model = new Inspection_Summary();
                    model.ProjectId = pid;
                    model.CompileDateMonth = this.drpCompileDateMonth.Text.Trim();
                    model.InspectionSummaryId = Guid.NewGuid().ToString();
                    model.InspectionSummaryMbId = "27";
                    model.SummeryResult = "";
                    allList.Add(model);
                    #endregion
                }
            }
            InspectionSummaryService.AddAll(allList);
            #endregion
            ShowNotify("生成成功!", MessageBoxIcon.Success);
            BindGrid();
            PageContext.RegisterStartupScript("CloseRefresh()");
        }
        #endregion
        #region 查询事件
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.drpCompileDateMonth.Text.Trim()))
            {
                ShowNotify("日期不能为空。", MessageBoxIcon.Warning);
                PageContext.RegisterStartupScript("CloseRefresh()");
                return;
            }
            //根据日期来加载 先判断有没有,没有则提示生成。
            var count = Funs.DB.Inspection_Summary.Where(x => x.CompileDateMonth == this.drpCompileDateMonth.Text.Trim()).ToList().Count();
            if (count == 0)
            {
                BindGrid();
                ShowNotify("当前日期暂无数据,请点击生成。", MessageBoxIcon.Warning);
                PageContext.RegisterStartupScript("CloseRefresh()");
                return;
            }
            BindGrid();
            PageContext.RegisterStartupScript("CloseRefresh()");
        }
        #endregion
        #region 加载数据
        private void BindGrid()
        {
            DataTable table = new DataTable();
            table.Columns.Add(new DataColumn("SNumber", typeof(string)));
            table.Columns.Add(new DataColumn("ModuleName", typeof(string)));
            table.Columns.Add(new DataColumn("MenuP", typeof(string)));
            table.Columns.Add(new DataColumn("MenuC", typeof(string)));
            table.Columns.Add(new DataColumn("InspectionSummaryId", typeof(string)));
            var list = Funs.DB.Base_Project.Where(x => x.ProjectState == Const.ProjectState_1 || x.ProjectState == null).OrderBy(x => x.ProjectCode).ToList();
            for (int i = 0; i < list.Count; i++)
            {
                //当前数值的列
                table.Columns.Add(new DataColumn("ThisProject" + (i + 1).ToString(), typeof(string)));
                //当前日期的列
                table.Columns.Add(new DataColumn("CompileDate" + (i + 1).ToString(), typeof(string)));
            }
            DataRow row;
            var SumModels = Funs.DB.Inspection_Summary.Where(x =>  x.CompileDateMonth == this.drpCompileDateMonth.Text.Trim()).FirstOrDefault();
            if (SumModels == null)
            {
                table = null;
                Grid1.DataSource = table;
                Grid1.DataBind();
                return;
            }
            else {
                using (Model.SGGLDB db = new Model.SGGLDB(Funs.ConnString))
                {
                    //首先获取模板表
                    var mbList = db.Inspection_SummaryMb.OrderBy(x => x.SortId).ToList();
                    for (int i = 0; i < mbList.Count; i++)
                    {
                        row = table.NewRow();
                        row[0] = mbList[i].SNumber;
                        row[1] = mbList[i].ModuleName;
                        row[2] = mbList[i].MenuP;
                        row[3] = mbList[i].MenuC;
                        row[4] = Guid.NewGuid().ToString();
                        int indexMb = 5;
                        //开始获取每列项目的数据
                        for (int k = 0; k < list.Count; k++)
                        {
                            var SumModel = db.Inspection_Summary.Where(x => x.ProjectId == list[k].ProjectId
                            && x.InspectionSummaryMbId == mbList[i].InspectionSummaryMbId
                            && x.CompileDateMonth == this.drpCompileDateMonth.Text.Trim()).FirstOrDefault();
                            row[indexMb] = SumModel.SummeryResult;
                            indexMb += 1;
                            row[indexMb] = SumModel.CompileDate.ToString().Split(' ')[0].Replace('/','-');
                            indexMb += 1;
                        }
                        table.Rows.Add(row);
                    }
                }
            }
            Grid1.DataSource = table;
            Grid1.DataBind();
        }
        #endregion
        #region 导出excel
        protected void btnOut_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            var FileName = "各项目巡查汇总(" + this.drpCompileDateMonth.Text.Trim() + ")";
            Response.AddHeader("content-disposition", "attachment; filename="+ FileName + ".xls");
            Response.ContentType = "application/vnd.ms-excel";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.Write(GetGridTableHtml(Grid1));
            Response.End();
        }
        #endregion
        /// 
        /// 格式化html
        /// 
        /// 
        /// 
        private string GetGridTableHtml(Grid grid)
        {
            StringBuilder sb = new StringBuilder();
            MultiHeaderTable mht = new MultiHeaderTable();
            mht.ResolveMultiHeaderTable(Grid1.Columns);
            sb.Append("");
            sb.Append("");
            ////列数
            //var rowCount = "";
            //var list = Funs.DB.Base_Project.Where(x => x.ProjectState == Const.ProjectState_1 || x.ProjectState == null).OrderBy(x => x.ProjectCode).ToList();
            //for (int i = 0; i < list.Count; i++)
            //{
            //    rowCount+="{}"
            //}
                foreach (List
");
            return sb.ToString();
        }
        public static string MidStrEx(string sourse, string startstr, string endstr)
        {
            string result = string.Empty;
            int startindex, endindex;
            try
            {
                startindex = sourse.IndexOf(startstr);
                if (startindex == -1)
                    return result;
                string tmpstr = sourse.Substring(startindex + startstr.Length);
                endindex = tmpstr.IndexOf(endstr);
                if (endindex == -1)
                    return result;
                result = tmpstr.Remove(endindex);
            }
            catch (Exception ex)
            {
                
            }
            return result;
        }
        #region 多表头处理
        /// 
        /// 处理多表头的类
        /// 
        public class MultiHeaderTable
        {
            // 包含 rowspan,colspan 的多表头,方便生成 HTML 的 table 标签
            public List> MultiTable = new List>();
            // 最终渲染的列数组
            public List Columns = new List();
            public void ResolveMultiHeaderTable(GridColumnCollection columns)
            {
                List