using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using AspNet = System.Web.UI.WebControls;
namespace FineUIPro.Web.CQMS.ManageReport
{
    public partial class WeekReportEdit : PageBase
    {
        #region 定义项
        /// 
        /// 主键
        /// 
        public string ReportId
        {
            get
            {
                return (string)ViewState["ReportId"];
            }
            set
            {
                ViewState["ReportId"] = value;
            }
        }
        /// 
        /// 定义本周主要工作内容集合
        /// 
        public static List thisWeekOrMonthContentLists = new List();
        /// 
        /// 定义原材料问题集合
        /// 
        public static List rowMaterialProblemLists = new List();
        /// 
        /// 定义施工过程问题
        /// 
        public static List constructionProblemsLists = new List();
        /// 
        /// 定义下周质量控制重点集合
        /// 
        public static List nextQualityControlLists = new List();
        #endregion
        #region 加载页面
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.EnableViewState = true;
                this.lblProjectName.Text = BLL.ProjectService.GetProjectByProjectId(this.CurrUser.LoginProjectId).ProjectName;
                this.ReportId = Request.Params["reportId"];
                if (!string.IsNullOrEmpty(Request.Params["view"]))
                {
                    this.btnSave.Visible = false;
                    this.btnPrint.Visible = false;
                }
                if (!string.IsNullOrEmpty(this.ReportId))
                {
                    Model.Report_WeekAndMonthReport weekAndMonthReport = BLL.WeekAndMonthReportService.GetWeekAndMonthReportById(this.ReportId);
                    if (weekAndMonthReport != null)
                    {
                        if (weekAndMonthReport.Period != null)
                        {
                            this.txtPeriod.Text = Convert.ToString(weekAndMonthReport.Period);
                        }
                        if (weekAndMonthReport.StartDate != null)
                        {
                            this.txtStartDate.Text = string.Format("{0:yyyy-MM-dd}", weekAndMonthReport.StartDate);
                        }
                        if (weekAndMonthReport.EndDate != null)
                        {
                            this.txtEndDate.Text = string.Format("{0:yyyy-MM-dd}", weekAndMonthReport.EndDate);
                        }
                    }
                    //this.txtPeriod.ReadOnly = true;
                    //this.txtStartDate.Enabled = false;
                    //this.txtEndDate.Enabled = false;
                    GetThisWeekOrMonthContentList(this.ReportId);//本月主要工作内容
                    GetRowMaterialProblemList(this.ReportId);//原材料问题
                    GetConstructionProblemsList(this.ReportId);//施工过程问题
                    GetNextQualityControlList(this.ReportId);//下月质量控制重点
                }
                else
                {
                    //this.txtStartDate.Text = string.IsNullOrEmpty(Request.Params["startdate"]) ? string.Format("{0:yyyy-MM-dd}", DateTime.Now) : Request.Params["startdate"];
                    // this.txtEndDate.Text = string.IsNullOrEmpty(Request.Params["enddate"]) ? string.Format("{0:yyyy-MM-dd}", Convert.ToDateTime(this.txtStartDate.Text).AddMonths(1).AddDays(-1)) : Request.Params["enddate"];
                    this.txtStartDate.Text = string.IsNullOrEmpty(Request.Params["startdate"]) ? string.Format("{0:yyyy-MM-dd}", DateTime.Now.AddDays(-6)) : Request.Params["startdate"];
                    this.txtEndDate.Text = string.IsNullOrEmpty(Request.Params["enddate"]) ? string.Format("{0:yyyy-MM-dd}", DateTime.Now) : Request.Params["enddate"];
                    //this.txtStartDate.Text = string.Format("{0:yyyy-MM-dd}", "2022-11-02 01:01:00");
                    //this.txtEndDate.Text = string.Format("{0:yyyy-MM-dd}", "2023-10-18 01:01:00");
                }
                CheckLotBindStatisc("CV");//检验批统计:土建
                CheckLotBindStatisc("EQ");//检验批统计:设备
                CheckLotBindStatisc("PP");//检验批统计:管道
                CheckLotBindStatisc("EL");//检验批统计:电气
                CheckLotBindStatisc("IN");//检验批统计:仪表
                CheckLotBindStatisc("FF");//检验批统计:反腐
                CheckLotBindStatisc("XF");//检验批统计:消防
                GetComprehensive();//综合管理
                BindStatisc();//无损检测统计
                NCRBindStatisc();//NCR统计
                DesignChangeOrderBindStatisc();//设计变更统计
                PassWelderBindStatisc();//合格焊工统计
                ConstructionStatisticsr();//施工方案统计
            }
        }
        /// 
        /// 综合管理
        /// 
        private void GetComprehensive()
        {
            decimal? count = 0;
            var inspectionEquipments = (from x in Funs.DB.Comprehensive_InspectionEquipment where x.ProjectId == this.CurrUser.LoginProjectId && x.CNProfessionalId == BLL.Const.EQCNProfessionalId && x.EquipmentOrMatail == "设备" select x).ToList();
            foreach (var item in inspectionEquipments)
            {
                count += Funs.GetNewIntOrZero(item.Counts);
            }
            this.txt3.Text = Convert.ToString(count);
            decimal? thisWeekCount = 0;
            var equpments = (from x in Funs.DB.Comprehensive_InspectionEquipment where x.ProjectId == this.CurrUser.LoginProjectId && x.CNProfessionalId == BLL.Const.EQCNProfessionalId && x.EquipmentOrMatail == "设备" && x.InspectionDate >= Convert.ToDateTime(this.txtStartDate.Text) && x.InspectionDate <= Convert.ToDateTime(this.txtEndDate.Text) select x).ToList();
            foreach (var item in equpments)
            {
                thisWeekCount += Funs.GetNewIntOrZero(item.Counts);
            }
            this.txt2.Text = Convert.ToString(thisWeekCount);
            //if (Convert.ToDecimal(this.txt3.Text.Trim()) > 0)
            //{
            //    this.txt4.Text = Math.Round((double)(Convert.ToDecimal(this.txt2.Text.Trim()) / Convert.ToDecimal(this.txt3.Text.Trim())) * 100, 2) + "%";
            //}
            //else
            //{
            //    this.txt4.Text = "0";
            //}
            var Uequipments = (from x in Funs.DB.Comprehensive_InspectionEquipment
                               where x.ProjectId == this.CurrUser.LoginProjectId
                               && x.EquipmentOrMatail == "材料"
                               && x.InspectionDate >= Convert.ToDateTime(this.txtStartDate.Text)
                               && x.InspectionDate <= Convert.ToDateTime(this.txtEndDate.Text)
                               && x.UnitId == BLL.Const.UnitId_CWCEC
                               select x).Count();
            this.txt5.Text = Uequipments.ToString();
            var Tequipments = (from x in Funs.DB.Comprehensive_InspectionEquipment
                               where x.ProjectId == this.CurrUser.LoginProjectId
                               && x.EquipmentOrMatail == "材料"
                               && x.UnitId == BLL.Const.UnitId_CWCEC
                               select x).Count();
            this.txt6.Text = Tequipments.ToString();
            var CUequipments = (from x in Funs.DB.Comprehensive_InspectionEquipment
                                where x.ProjectId == this.CurrUser.LoginProjectId
                                && x.EquipmentOrMatail == "材料"
                                && x.InspectionDate >= Convert.ToDateTime(this.txtStartDate.Text)
                                && x.InspectionDate <= Convert.ToDateTime(this.txtEndDate.Text)
                                && x.UnitId != BLL.Const.UnitId_CWCEC
                                select x).Count();
            this.txt7.Text = CUequipments.ToString();
            var CTequipments = (from x in Funs.DB.Comprehensive_InspectionEquipment
                                where x.ProjectId == this.CurrUser.LoginProjectId
                                && x.EquipmentOrMatail == "材料"
                                && x.UnitId != BLL.Const.UnitId_CWCEC
                                select x).Count();
            this.txt8.Text = CTequipments.ToString();
            if (this.ReportId != null)
            {
                var q = BLL.ComprehensiveService.GetComprehensiveByReportId(this.ReportId);
                if (q != null)
                {
                    this.txt1.Text = q.TotalCount.HasValue ? q.TotalCount.Value.ToString() : "";
                    this.txt4.Text = q.EquipmentRate;
                    this.txt9.Text = q.Others;
                }
                else
                {
                    this.txt1.Text = string.Empty;
                    this.txt4.Text = string.Empty;
                    this.txt9.Text = string.Empty;
                }
            }
        }
        /// 
        /// 计算设备报验比率
        /// 
        /// 
        /// 
        protected void txt1_TextChanged(object sender, EventArgs e)
        {
            try
            {
                int i = Convert.ToInt32(this.txt3.Text.Trim());
                if (txt1.Text != "0" && txt1.Text != string.Empty)
                {
                    this.txt4.Text = Math.Round((double)(i / (double)Convert.ToInt32(this.txt1.Text.Trim())) * 100, 2) + "%";
                }
            }
            catch
            {
                ScriptManager.RegisterStartupScript(this, typeof(string), "_alert", "alert('输入格式错误,【台数】必须是整数!')", true);
                return;
            }
        }
        /// 
        /// 本月主要工作内容
        /// 
        private void GetThisWeekOrMonthContentList(string reportId)
        {
            thisWeekOrMonthContentLists = BLL.ThisWeekOrMonthContentService.GetThisWeekOrMonthContentByReportId(reportId);
            this.gvThisWeekOrMonthContent.DataSourceID = null;
            this.gvThisWeekOrMonthContent.DataSource = thisWeekOrMonthContentLists;
            this.gvThisWeekOrMonthContent.DataBind();
        }
        /// 
        /// 原材料问题
        /// 
        /// 
        private void GetRowMaterialProblemList(string reportId)
        {
            rowMaterialProblemLists = BLL.RowMaterialProblemService.GetRowMaterialProblemByReportId(reportId);
            this.gvRowMaterialProblem.DataSourceID = null;
            this.gvRowMaterialProblem.DataSource = rowMaterialProblemLists;
            this.gvRowMaterialProblem.DataBind();
        }
        /// 
        /// 施工过程问题
        /// 
        /// 
        private void GetConstructionProblemsList(string reportId)
        {
            constructionProblemsLists = BLL.ConstructionProblemsService.GetConstructionProblemsByReportId(reportId);
            this.gvConstructionProblems.DataSourceID = null;
            this.gvConstructionProblems.DataSource = constructionProblemsLists;
            this.gvConstructionProblems.DataBind();
        }
        /// 
        /// 下月质量控制重点
        /// 
        /// 
        private void GetNextQualityControlList(string reportId)
        {
            nextQualityControlLists = BLL.NextQualityControlService.GetNextQualityControlByReportId(reportId);
            this.gvNextQualityControl.DataSourceID = null;
            this.gvNextQualityControl.DataSource = nextQualityControlLists;
            this.gvNextQualityControl.DataBind();
        }
        #endregion
        #region 本月主要内容
        /// 
        /// 增加本月主要内容
        /// 
        /// 
        /// 
        protected void btnAddThisWeekAndMonthContent_Click(object sender, ImageClickEventArgs e)
        {
            thisWeekOrMonthContentLists.Clear();
            saveThisWeekAndMonthContent();
            Model.Report_ThisWeekOrMonthContent newThisWeekOrMonthContent = new Model.Report_ThisWeekOrMonthContent();
            newThisWeekOrMonthContent.ContentId = SQLHelper.GetNewID(typeof(Model.Report_ThisWeekOrMonthContent));
            thisWeekOrMonthContentLists.Add(newThisWeekOrMonthContent);
            this.gvThisWeekOrMonthContent.DataSourceID = null;
            this.gvThisWeekOrMonthContent.DataSource = thisWeekOrMonthContentLists;
            this.gvThisWeekOrMonthContent.DataBind();
        }
        /// 
        /// 检查并保存本月主要内容集合
        /// 
        private void saveThisWeekAndMonthContent()
        {
            thisWeekOrMonthContentLists.Clear();
            for (int i = 0; i < gvThisWeekOrMonthContent.Rows.Count; i++)
            {
                Model.Report_ThisWeekOrMonthContent newThisWeekOrMonthContent = new Model.Report_ThisWeekOrMonthContent();
                AspNet.TextBox txtContents = (AspNet.TextBox)(this.gvThisWeekOrMonthContent.Rows[i].FindControl("txtContents"));
                AspNet.Label lblContentId = (AspNet.Label)(this.gvThisWeekOrMonthContent.Rows[i].FindControl("lblContentId"));
                newThisWeekOrMonthContent.Contents = txtContents.Text.Trim();
                newThisWeekOrMonthContent.ContentId = lblContentId.Text.Trim();
                thisWeekOrMonthContentLists.Add(newThisWeekOrMonthContent);
            }
        }
        /// 
        /// 本月主要内容行点击事件
        /// 
        /// 
        /// 
        protected void gvThisWeekOrMonthContent_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            saveThisWeekAndMonthContent();
            string contentId = e.CommandArgument.ToString();
            if (e.CommandName == "del")
            {
                foreach (Model.Report_ThisWeekOrMonthContent item in thisWeekOrMonthContentLists)
                {
                    if (item.ContentId == contentId)
                    {
                        thisWeekOrMonthContentLists.Remove(item);
                        break;
                    }
                }
                this.gvThisWeekOrMonthContent.DataSourceID = null;
                this.gvThisWeekOrMonthContent.DataSource = thisWeekOrMonthContentLists;
                this.gvThisWeekOrMonthContent.DataBind();
            }
        }
        #endregion
        #region 原材料问题
        /// 
        /// 增加原材料问题
        /// 
        /// 
        /// 
        protected void btnAddRowMaterialProblem_Click(object sender, ImageClickEventArgs e)
        {
            rowMaterialProblemLists.Clear();
            saveRowMaterialProblem();
            Model.Report_RowMaterialProblem newRowMaterialProblem = new Model.Report_RowMaterialProblem();
            newRowMaterialProblem.RowMaterialProblemId = SQLHelper.GetNewID(typeof(Model.Report_RowMaterialProblem));
            rowMaterialProblemLists.Add(newRowMaterialProblem);
            this.gvRowMaterialProblem.DataSourceID = null;
            this.gvRowMaterialProblem.DataSource = rowMaterialProblemLists;
            this.gvRowMaterialProblem.DataBind();
        }
        /// 
        /// 检查并保存原材料问题集合
        /// 
        private void saveRowMaterialProblem()
        {
            rowMaterialProblemLists.Clear();
            for (int i = 0; i < gvRowMaterialProblem.Rows.Count; i++)
            {
                Model.Report_RowMaterialProblem newRowMaterialProblem = new Model.Report_RowMaterialProblem();
                AspNet.TextBox txtUnit = (AspNet.TextBox)(this.gvRowMaterialProblem.Rows[i].FindControl("txtUnit"));
                AspNet.TextBox txtProblemDesrioption = (AspNet.TextBox)(this.gvRowMaterialProblem.Rows[i].FindControl("txtProblemDesrioption"));
                AspNet.TextBox txtTreatmentMeasures = (AspNet.TextBox)(this.gvRowMaterialProblem.Rows[i].FindControl("txtTreatmentMeasures"));
                AspNet.TextBox txtProcessingResults = (AspNet.TextBox)(this.gvRowMaterialProblem.Rows[i].FindControl("txtProcessingResults"));
                AspNet.TextBox txtRemark = (AspNet.TextBox)(this.gvRowMaterialProblem.Rows[i].FindControl("txtRemark"));
                AspNet.Label lblRowMaterialProblemId = (AspNet.Label)(this.gvRowMaterialProblem.Rows[i].FindControl("lblRowMaterialProblemId"));
                newRowMaterialProblem.UnitId = txtUnit.Text.Trim();
                newRowMaterialProblem.ProblemDesrioption = txtProblemDesrioption.Text.Trim();
                newRowMaterialProblem.TreatmentMeasures = txtTreatmentMeasures.Text.Trim();
                newRowMaterialProblem.ProcessingResults = txtProcessingResults.Text.Trim();
                newRowMaterialProblem.Remark = txtRemark.Text.Trim();
                newRowMaterialProblem.RowMaterialProblemId = lblRowMaterialProblemId.Text.Trim();
                rowMaterialProblemLists.Add(newRowMaterialProblem);
            }
        }
        /// 
        /// 原材料问题行点击事件
        /// 
        /// 
        /// 
        protected void gvRowMaterialProblem_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            saveRowMaterialProblem();
            string rowMaterialProblemId = e.CommandArgument.ToString();
            if (e.CommandName == "del")
            {
                foreach (Model.Report_RowMaterialProblem item in rowMaterialProblemLists)
                {
                    if (item.RowMaterialProblemId == rowMaterialProblemId)
                    {
                        rowMaterialProblemLists.Remove(item);
                        break;
                    }
                }
                this.gvRowMaterialProblem.DataSourceID = null;
                this.gvRowMaterialProblem.DataSource = rowMaterialProblemLists;
                this.gvRowMaterialProblem.DataBind();
            }
        }
        #endregion
        #region 施工过程问题
        /// 
        /// 增加施工过程问题
        /// 
        /// 
        /// 
        protected void btnAddConstructionProblems_Click(object sender, ImageClickEventArgs e)
        {
            constructionProblemsLists.Clear();
            saveConstructionProblems();
            Model.Report_ConstructionProblems newConstructionProblems = new Model.Report_ConstructionProblems();
            newConstructionProblems.ConstructionProblemsId = SQLHelper.GetNewID(typeof(Model.Report_ConstructionProblems));
            constructionProblemsLists.Add(newConstructionProblems);
            this.gvConstructionProblems.DataSourceID = null;
            this.gvConstructionProblems.DataSource = constructionProblemsLists;
            this.gvConstructionProblems.DataBind();
        }
        /// 
        /// 检查并保存施工过程问题集合
        /// 
        private void saveConstructionProblems()
        {
            constructionProblemsLists.Clear();
            for (int i = 0; i < this.gvConstructionProblems.Rows.Count; i++)
            {
                Model.Report_ConstructionProblems newConstructionProblems = new Model.Report_ConstructionProblems();
                AspNet.DropDownList drpUnitId = (AspNet.DropDownList)(this.gvConstructionProblems.Rows[i].FindControl("drpUnitId"));
                AspNet.TextBox txtProblemDesrioption = (AspNet.TextBox)(this.gvConstructionProblems.Rows[i].FindControl("txtProblemDesrioption"));
                AspNet.TextBox txtTreatmentMeasures = (AspNet.TextBox)(this.gvConstructionProblems.Rows[i].FindControl("txtTreatmentMeasures"));
                AspNet.TextBox txtProcessingResults = (AspNet.TextBox)(this.gvConstructionProblems.Rows[i].FindControl("txtProcessingResults"));
                AspNet.TextBox txtRemark = (AspNet.TextBox)(this.gvConstructionProblems.Rows[i].FindControl("txtRemark"));
                AspNet.Label lblConstructionProblemsId = (AspNet.Label)(this.gvConstructionProblems.Rows[i].FindControl("lblConstructionProblemsId"));
                if (drpUnitId.SelectedValue != "0")
                {
                    newConstructionProblems.UnitId = drpUnitId.SelectedValue;
                }
                newConstructionProblems.ProblemDesrioption = txtProblemDesrioption.Text.Trim();
                newConstructionProblems.TreatmentMeasures = txtTreatmentMeasures.Text.Trim();
                newConstructionProblems.ProcessingResults = txtProcessingResults.Text.Trim();
                newConstructionProblems.Remark = txtRemark.Text.Trim();
                newConstructionProblems.ConstructionProblemsId = lblConstructionProblemsId.Text.Trim();
                constructionProblemsLists.Add(newConstructionProblems);
            }
        }
        /// 
        /// 施工过程问题行点击事件
        /// 
        /// 
        /// 
        protected void gvConstructionProblems_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            saveConstructionProblems();
            string constructionProblemsId = e.CommandArgument.ToString();
            if (e.CommandName == "del")
            {
                foreach (Model.Report_ConstructionProblems item in constructionProblemsLists)
                {
                    if (item.ConstructionProblemsId == constructionProblemsId)
                    {
                        constructionProblemsLists.Remove(item);
                        break;
                    }
                }
                this.gvConstructionProblems.DataSourceID = null;
                this.gvConstructionProblems.DataSource = constructionProblemsLists;
                this.gvConstructionProblems.DataBind();
            }
        }
        /// 
        /// 绑定行后激发
        /// 
        /// 
        /// 
        protected void gvConstructionProblems_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            for (int i = 0; i < this.gvConstructionProblems.Rows.Count; i++)
            {
                AspNet.DropDownList drpUnitId = (AspNet.DropDownList)(this.gvConstructionProblems.Rows[i].FindControl("drpUnitId"));
                AspNet.HiddenField hdUnitId = (AspNet.HiddenField)(this.gvConstructionProblems.Rows[i].FindControl("hdUnitId"));
                Funs.PleaseSelect(drpUnitId);
                drpUnitId.Items.AddRange(BLL.UnitService.drpUnitItemListByProjectId(this.CurrUser.LoginProjectId));
                if (!string.IsNullOrEmpty(hdUnitId.Value))
                {
                    drpUnitId.SelectedValue = hdUnitId.Value;
                }
            }
        }
        #endregion
        #region 检验批统计
        #region 绑定GridView
        /// 
        /// 绑定
        /// 
        /// 
        public void CheckLotBindStatisc(string cNProfessionalCode)
        {
            DateTime startDate = Convert.ToDateTime(this.txtStartDate.Text.Trim());
            DateTime endDate = Convert.ToDateTime(this.txtEndDate.Text.Trim());
            DateTime projectStartDate = Convert.ToDateTime("2015-01-01");
            List StatisticsList = new List();
            Model.Base_Project project = BLL.ProjectService.GetProjectByProjectId(this.CurrUser.LoginProjectId);
            if (project != null)
            {
                if (project.StartDate != null)
                {
                    projectStartDate = Convert.ToDateTime(project.StartDate);
                }
            }
            int i = 1;
            string cNProfessionalId = (from x in Funs.DB.Base_CNProfessional where x.CNProfessionalCode == cNProfessionalCode select x.CNProfessionalId).FirstOrDefault();
            List workNames = new List();
            //专业下所有集合
            List totalManagementList = BLL.InspectionManagementService.getInspectionManagementDetailListByCNProfessionalIdAndDate(this.CurrUser.LoginProjectId, cNProfessionalId, projectStartDate, endDate, false);
            //专业下当期集合
            List managementList = BLL.InspectionManagementService.getInspectionManagementDetailListByCNProfessionalIdAndDate(this.CurrUser.LoginProjectId, cNProfessionalId, startDate, endDate, false);
            workNames = totalManagementList.Select(x => x.UnitWorkId).DefaultIfEmpty().Distinct()?.ToList();
            foreach (string item in workNames)
            {
                Model.WBS_UnitWork ins = BLL.UnitWorkService.GetUnitWorkByUnitWorkId(item);
                if (ins != null)
                {
                    Model.CheckStatisc checkStatisc = new Model.CheckStatisc();
                    checkStatisc.Num = i;
                    checkStatisc.WorkName = ins.UnitWorkName;
                    checkStatisc.CheckNum = managementList.Count(x => x.UnitWorkId == item);
                    checkStatisc.TotalCheckNum = totalManagementList.Count(x => x.UnitWorkId == item);
                    checkStatisc.OKNum = managementList.Count(x => x.UnitWorkId == item && x.IsOnceQualified == true);
                    checkStatisc.TotalOKNum = totalManagementList.Count(x => x.UnitWorkId == item && x.IsOnceQualified == true);
                    StatisticsList.Add(checkStatisc);
                }
            }
            //foreach (var item in totalManagementList)
            //{
            //    Model.WBS_BreakdownProject breakdownProject = BLL.BreakdownProjectService.GetBreakdownProjectById(item.ControlPointType);
            //    if (breakdownProject != null)
            //    {
            //        Model.WBS_DivisionProject divisionProject = BLL.DivisionProjectService.GetDivisionProjectById(breakdownProject.DivisionProjectId);
            //        if (divisionProject != null)
            //        {
            //            Model.WBS_UnitWork ins = BLL.UnitWorkService.GetUnitWorkByUnitWorkId(divisionProject.UnitWorkId);
            //            if (ins != null)
            //            {
            //                if (!workNames.Contains(ins.UnitWorkName))  //新增记录
            //                {
            //                    Model.CheckStatisc checkStatisc = new Model.CheckStatisc();
            //                    checkStatisc.Num = i;
            //                    checkStatisc.WorkName = ins.UnitWorkName;
            //                    workNames.Add(ins.UnitWorkName);
            //                    checkStatisc.CheckNum = managementList.Count(x => x.ControlPointType == item.ControlPointType);
            //                    checkStatisc.TotalCheckNum = totalManagementList.Count(x => x.ControlPointType == item.ControlPointType);
            //                    checkStatisc.OKNum = managementList.Count(x => x.ControlPointType == item.ControlPointType && x.IsOnceQualified == true);
            //                    checkStatisc.TotalOKNum = totalManagementList.Count(x => x.ControlPointType == item.ControlPointType && x.IsOnceQualified == true);
            //                    StatisticsList.Add(checkStatisc);
            //                    i++;
            //                }
            //                else   //更新已有记录
            //                {
            //                    Model.CheckStatisc checkStatisc1 = StatisticsList.FirstOrDefault(x => x.WorkName == ins.UnitWorkName);
            //                    checkStatisc1.CheckNum += managementList.Count(x => x.ControlPointType == item.ControlPointType);
            //                    checkStatisc1.TotalCheckNum += totalManagementList.Count(x => x.ControlPointType == item.ControlPointType);
            //                    checkStatisc1.OKNum += managementList.Count(x => x.ControlPointType == item.ControlPointType && x.IsOnceQualified == true);
            //                    checkStatisc1.TotalOKNum += totalManagementList.Count(x => x.ControlPointType == item.ControlPointType && x.IsOnceQualified == true);
            //                }
            //            }
            //        }
            //    }
            //}
            /*if (cNProfessionalId == BLL.Const.CNProfessionalCVId)    //土建按单位工程统计
            {
                
            }
            else
            {
                foreach (var item in totalManagementList)
                {
                    Model.WBS_BreakdownProject breakdownProject = BLL.BreakdownProjectService.GetBreakdownProjectById(item.ControlPointType);
                    if (breakdownProject != null)
                    {
                        Model.WBS_DivisionProject divisionProject = BLL.DivisionProjectService.GetDivisionProjectById(breakdownProject.DivisionProjectId);
                        if (divisionProject != null)
                        {
                            if (!workNames.Contains(divisionProject.DivisionName))  //新增记录
                            {
                                Model.CheckStatisc checkStatisc = new Model.CheckStatisc();
                                checkStatisc.Num = i;
                                checkStatisc.WorkName = divisionProject.DivisionName;
                                workNames.Add(divisionProject.DivisionName);
                                checkStatisc.CheckNum = managementList.Count(x => x.ControlPointType == item.ControlPointType);
                                checkStatisc.TotalCheckNum = totalManagementList.Count(x => x.ControlPointType == item.ControlPointType);
                                checkStatisc.OKNum = managementList.Count(x => x.ControlPointType == item.ControlPointType && x.IsOnceQualified == true);
                                checkStatisc.TotalOKNum = totalManagementList.Count(x => x.ControlPointType == item.ControlPointType && x.IsOnceQualified == true);
                                StatisticsList.Add(checkStatisc);
                                i++;
                            }
                            else   //更新已有记录
                            {
                                Model.CheckStatisc checkStatisc1 = StatisticsList.FirstOrDefault(x => x.WorkName == divisionProject.DivisionName);
                                checkStatisc1.CheckNum += managementList.Count(x => x.ControlPointType == item.ControlPointType);
                                checkStatisc1.TotalCheckNum += totalManagementList.Count(x => x.ControlPointType == item.ControlPointType);
                                checkStatisc1.OKNum += managementList.Count(x => x.ControlPointType == item.ControlPointType && x.IsOnceQualified == true);
                                checkStatisc1.TotalOKNum += totalManagementList.Count(x => x.ControlPointType == item.ControlPointType && x.IsOnceQualified == true);
                            }
                        }
                    }
                }
            }*/
            foreach (var item in StatisticsList)
            {
                if (item.CheckNum != 0)//被除数不能为零
                {
                    item.OneOKRate = Math.Round((double)item.OKNum / (double)item.CheckNum * 100, 2) + "%";//保留两位小数、后四舍五入
                }
                else
                {
                    item.OneOKRate = "0%";
                }
                if (item.TotalCheckNum != 0)//被除数不能为零
                {
                    item.TotalOneOKRate = Math.Round((double)item.TotalOKNum / (double)item.TotalCheckNum * 100, 2) + "%";//保留两位小数、后四舍五入
                }
                else
                {
                    item.TotalOneOKRate = "0%";
                }
            }
            if (StatisticsList.Count() > 0)   //增加总计
            {
                Model.CheckStatisc StatisticsLast = new Model.CheckStatisc();
                StatisticsLast.Num = StatisticsList.Count() + 1;
                StatisticsLast.WorkName = "合计";
                foreach (Model.CheckStatisc item in StatisticsList)
                {
                    StatisticsLast.CheckNum += item.CheckNum;
                    StatisticsLast.TotalCheckNum += item.TotalCheckNum;
                    StatisticsLast.OKNum += item.OKNum;
                    StatisticsLast.TotalOKNum += item.TotalOKNum;
                }
                if (StatisticsLast.CheckNum != 0)//被除数不能为零
                {
                    StatisticsLast.OneOKRate = Math.Round((double)StatisticsLast.OKNum / (double)StatisticsLast.CheckNum * 100, 2) + "%";//保留两位小数、后四舍五入
                }
                else
                {
                    StatisticsLast.OneOKRate = "0%";
                }
                if (StatisticsLast.TotalCheckNum != 0)//被除数不能为零
                {
                    StatisticsLast.TotalOneOKRate = Math.Round((double)StatisticsLast.TotalOKNum / (double)StatisticsLast.TotalCheckNum * 100, 2) + "%";//保留两位小数、后四舍五入
                }
                else
                {
                    StatisticsLast.TotalOneOKRate = "0%";
                }
                StatisticsList.Add(StatisticsLast);
            }
            else   //新增本周/月无验收数据的也需要列出表格
            {
                Model.CheckStatisc StatisticsLast = new Model.CheckStatisc();
                StatisticsLast.Num = StatisticsList.Count() + 1;
                StatisticsLast.WorkName = "合计";
                StatisticsLast.CheckNum = 0;
                StatisticsLast.TotalCheckNum = 0;
                StatisticsLast.OKNum = 0;
                StatisticsLast.TotalOKNum = 0;
                if (StatisticsLast.CheckNum != 0)//被除数不能为零
                {
                    StatisticsLast.OneOKRate = Math.Round((double)StatisticsLast.OKNum / (double)StatisticsLast.CheckNum * 100, 2) + "%";//保留两位小数、后四舍五入
                }
                else
                {
                    StatisticsLast.OneOKRate = "0%";
                }
                if (StatisticsLast.TotalCheckNum != 0)//被除数不能为零
                {
                    StatisticsLast.TotalOneOKRate = Math.Round((double)StatisticsLast.TotalOKNum / (double)StatisticsLast.TotalCheckNum * 100, 2) + "%";//保留两位小数、后四舍五入
                }
                else
                {
                    StatisticsLast.TotalOneOKRate = "0%";
                }
                StatisticsList.Add(StatisticsLast);
            }
            if (cNProfessionalCode == "CV")
            {
                this.gvTJ.DataSource = StatisticsList;
                this.gvTJ.DataBind();
            }
            if (cNProfessionalCode == "EQ")
            {
                this.gvSB.DataSource = StatisticsList;
                this.gvSB.DataBind();
            }
            if (cNProfessionalCode == "PP")
            {
                this.gvGD.DataSource = StatisticsList;
                this.gvGD.DataBind();
            }
            if (cNProfessionalCode == "EL")
            {
                this.gvDQ.DataSource = StatisticsList;
                this.gvDQ.DataBind();
            }
            if (cNProfessionalCode == "IN")
            {
                this.gvYB.DataSource = StatisticsList;
                this.gvYB.DataBind();
            }
            if (cNProfessionalCode == "FF")
            {
                this.gvFF.DataSource = StatisticsList;
                this.gvFF.DataBind();
            }
            if (cNProfessionalCode == "XF")
            {
                this.gvXF.DataSource = StatisticsList;
                this.gvXF.DataBind();
            }
        }
        #endregion
        /// 
        /// GridView创建行时激发
        /// 
        /// 
        /// 
        protected void gvTJ_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string headerStr = "序号#单位工程#检查(点) 本周,累计#合格(点) 本周,累计#一次合格率 本周,累计";
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        /// 
        /// GridView创建行时激发
        /// 
        /// 
        /// 
        protected void gvSB_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string headerStr = "序号#单位工程#检查(点) 本周,累计#合格(点) 本周,累计#一次合格率 本周,累计";
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        /// 
        /// GridView创建行时激发
        /// 
        /// 
        /// 
        protected void gvGD_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string headerStr = "序号#单位工程#检查(点) 本周,累计#合格(点) 本周,累计#一次合格率 本周,累计";
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        /// 
        /// GridView创建行时激发
        /// 
        /// 
        /// 
        protected void gvDQ_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string headerStr = "序号#单位工程#检查(点) 本周,累计#合格(点) 本周,累计#一次合格率 本周,累计";
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        /// 
        /// GridView创建行时激发
        /// 
        /// 
        /// 
        protected void gvYB_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string headerStr = "序号#单位工程#检查(点) 本周,累计#合格(点) 本周,累计#一次合格率 本周,累计";
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        /// 
        /// GridView创建行时激发
        /// 
        /// 
        /// 
        protected void gvFF_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string headerStr = "序号#单位工程#检查(点) 本周,累计#合格(点) 本周,累计#一次合格率 本周,累计";
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        /// 
        /// GridView创建行时激发
        /// 
        /// 
        /// 
        protected void gvXF_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string headerStr = "序号#单位工程#检查(点) 本周,累计#合格(点) 本周,累计#一次合格率 本周,累计";
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        #endregion
        #region 无损检测统计
        #region 绑定GridView
        /// 
        /// 绑定
        /// 
        /// 
        public void BindStatisc()
        {
            DateTime startDate = Convert.ToDateTime(this.txtStartDate.Text.Trim());
            DateTime endDate = Convert.ToDateTime(this.txtEndDate.Text.Trim());
            SqlParameter[] values = new SqlParameter[]
                {
                   new SqlParameter("@projectId", this.CurrUser.LoginProjectId),
                   new SqlParameter("@startDate",startDate),
                   new SqlParameter("@endDate",endDate)
                };
            DataTable dt = BLL.SQLHelper.GetDataTableRunProc("Sp_ProcessControl_NondestructiveTestStatisc", values);
            this.gvHJGLStatisc.DataSourceID = null;
            this.gvHJGLStatisc.DataSource = dt;
            this.gvHJGLStatisc.DataBind();
        }
        #endregion
        /// 
        /// 无损检测创建行时激发
        /// 
        /// 
        /// 
        protected void gvHJGLStatisc_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string headerStr = "序号#分包商#探伤部位#RT数量 本月,累计#一次合格 本月,累计#一次合格率 本月,累计";
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        #endregion
        #region NCR统计
        #region 绑定GridView
        /// 
        /// 绑定
        /// 
        /// 
        public void NCRBindStatisc()
        {
            DateTime startDate = Convert.ToDateTime(this.txtStartDate.Text.Trim());
            DateTime endDate = Convert.ToDateTime(this.txtEndDate.Text.Trim());
            List StatisticsList = new List();
            int i = 1;
            var project = BLL.ProjectService.GetProjectByProjectId(this.CurrUser.LoginProjectId);
            DateTime projectStartDate = Convert.ToDateTime("2000-01-01");
            if (project != null && project.StartDate != null)
            {
                projectStartDate = project.StartDate.Value;
            }
            var units = from x in Funs.DB.Project_ProjectUnit
                        join y in Funs.DB.Base_Unit on x.UnitId equals y.UnitId
                        where x.ProjectId == this.CurrUser.LoginProjectId && x.UnitType == BLL.Const.ProjectUnitType_2
                        orderby y.UnitCode
                        select new { x.UnitId, y.UnitName };
            var db = Funs.DB;
            foreach (var item in units)
            {
                var query = from c in db.Comprehensive_NCRManagement
                            join u in db.Base_Unit on c.ReceiveUnit equals u.UnitId into unitJoin
                            from u in unitJoin.DefaultIfEmpty()
                            where c.ProjectId == this.CurrUser.LoginProjectId && c.ReceiveUnit == item.UnitId
                            select new
                            {
                                c.NCRManagementId,
                                c.ProjectId,
                                u.UnitId,
                                u.UnitName,
                                c.IssuedDate,
                                c.Status,
                                c.ImplementationFrontState,
                            };
                var AllList = query.ToList();
                var unitNCRStatic = query
                    .Where(x => (x.IssuedDate >= Convert.ToDateTime(startDate) && x.IssuedDate <= Convert.ToDateTime(endDate)));
                Model.NCRReportStatisc NCRStatisc = new Model.NCRReportStatisc();
                NCRStatisc.Num = i;
                NCRStatisc.WorkName = item.UnitName;
                //NCRStatisc.CurrentPeriodOkNum = unitNCRStatic.Count(x => x.Status == "3");
                //NCRStatisc.OKNum = AllList.Count(x => x.Status == "3");
                //NCRStatisc.CurrentPeriodOkNum = unitNCRStatic.Where(x => x.ImplementationFrontState.Trim().Equals("已闭合")).Count();
                //NCRStatisc.OKNum = AllList.Where(x => x.ImplementationFrontState.Trim().Equals("已闭合")).Count();
                NCRStatisc.CurrentPeriodOkNum = unitNCRStatic.Where(x => x.ImplementationFrontState == "已闭合").Count();
                NCRStatisc.OKNum = AllList.Where(x => x.ImplementationFrontState == "已闭合").Count();
                NCRStatisc.CheckNum = AllList.Count();
                if (NCRStatisc.CheckNum != 0)//被除数不能为零
                {
                    NCRStatisc.OKRate = Math.Round((double)NCRStatisc.OKNum / (double)NCRStatisc.CheckNum * 100, 2) + "%";//保留两位小数、后四舍五入
                }
                else
                {
                    NCRStatisc.OKRate = "0%";
                }
                StatisticsList.Add(NCRStatisc);
                i++;
            }
            if (StatisticsList.Count() > 0)   //增加总计
            {
                Model.NCRReportStatisc StatisticsLast = new Model.NCRReportStatisc();
                StatisticsLast.Num = StatisticsList.Count() + 1;
                StatisticsLast.WorkName = "合计";
                foreach (Model.NCRReportStatisc item in StatisticsList)
                {
                    StatisticsLast.CurrentPeriodOkNum += item.CurrentPeriodOkNum;
                    StatisticsLast.OKNum += item.OKNum;
                    StatisticsLast.CheckNum += item.CheckNum;
                }
                if (StatisticsLast.CheckNum != 0)//被除数不能为零
                {
                    StatisticsLast.OKRate = Math.Round((double)StatisticsLast.OKNum / (double)StatisticsLast.CheckNum * 100, 2) + "%";//保留两位小数、后四舍五入
                }
                else
                {
                    StatisticsLast.OKRate = "0%";
                }
                StatisticsList.Add(StatisticsLast);
            }
            else
            {
                Model.NCRReportStatisc StatisticsLast = new Model.NCRReportStatisc();
                StatisticsLast.Num = 0;
                StatisticsLast.WorkName = "合计";
                StatisticsLast.CurrentPeriodOkNum = 0;
                StatisticsLast.OKNum = 0;
                StatisticsLast.CheckNum = 0;
                StatisticsLast.OKRate = "0%";
                StatisticsList.Add(StatisticsLast);
            }
            this.gvNCRStatisc.DataSource = StatisticsList;
            this.gvNCRStatisc.DataBind();
        }
        #endregion
        /// 
        /// NCR行创建时激发
        /// 
        /// 
        /// 
        protected void gvNCRStatisc_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string headerStr = "序号#接收单位#本月已完成#累计已完成#NCR总数#累计完成比例";
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        #endregion
        #region 设计变更统计
        #region 绑定GridView
        /// 
        /// 绑定
        /// 
        /// 
        public void DesignChangeOrderBindStatisc()
        {
            DateTime startDate = Convert.ToDateTime(this.txtStartDate.Text.Trim());
            DateTime endDate = Convert.ToDateTime(this.txtEndDate.Text.Trim());
            DateTime projectStartDate = Convert.ToDateTime("2015-01-01");
            List StatisticsList = new List();
            Model.Base_Project project = BLL.ProjectService.GetProjectByProjectId(this.CurrUser.LoginProjectId);
            if (project != null)
            {
                if (project.StartDate != null)
                {
                    projectStartDate = Convert.ToDateTime(project.StartDate);
                }
            }
            int i = 1;
            var cNProfessionals = from x in Funs.DB.Base_CNProfessional orderby x.SortIndex select x;
            foreach (var item in cNProfessionals)
            {
                //专业下所有集合
                List totalManagementList = BLL.DesignChangeOrderService.GetDesignChangeOrderListByCNProfessionalIdAndDate(this.CurrUser.LoginProjectId, item.CNProfessionalId, projectStartDate, DateTime.Now);
                //专业下当期集合
                List managementList = BLL.DesignChangeOrderService.GetDesignChangeOrderListByCNProfessionalIdAndDate(this.CurrUser.LoginProjectId, item.CNProfessionalId, startDate, endDate);
                Model.CheckStatisc checkStatisc = new Model.CheckStatisc();
                checkStatisc.Num = i;
                checkStatisc.WorkName = item.ProfessionalName;
                checkStatisc.CheckNum = managementList.Count();
                checkStatisc.TotalCheckNum = totalManagementList.Count();
                checkStatisc.OKNum = managementList.Count(x => x.ApprovalDate != null);
                checkStatisc.TotalOKNum = totalManagementList.Count(x => x.ApprovalDate != null);
                checkStatisc.OneOKRate = managementList.Count(x => x.Status == "3").ToString();       //当期完成数
                checkStatisc.TotalOneOKRate = totalManagementList.Count(x => x.Status == "3").ToString();    //累计完成数
                if (checkStatisc.CheckNum > 0 || checkStatisc.TotalCheckNum > 0 || checkStatisc.OKNum > 0 || checkStatisc.TotalOKNum > 0)
                {
                    StatisticsList.Add(checkStatisc);
                    i++;
                }
            }
            if (StatisticsList.Count() > 0)   //增加总计
            {
                Model.CheckStatisc StatisticsLast = new Model.CheckStatisc();
                StatisticsLast.Num = StatisticsList.Count() + 1;
                StatisticsLast.WorkName = "合计";
                foreach (Model.CheckStatisc item in StatisticsList)
                {
                    StatisticsLast.CheckNum += item.CheckNum;
                    StatisticsLast.TotalCheckNum += item.TotalCheckNum;
                    StatisticsLast.OKNum += item.OKNum;
                    StatisticsLast.TotalOKNum += item.TotalOKNum;
                    StatisticsLast.OneOKRate = (Convert.ToInt32(StatisticsLast.OneOKRate) + Convert.ToInt32(item.OneOKRate)).ToString();
                    StatisticsLast.TotalOneOKRate = (Convert.ToInt32(StatisticsLast.TotalOneOKRate) + Convert.ToInt32(item.TotalOneOKRate)).ToString();
                }
                StatisticsList.Add(StatisticsLast);
            }
            this.gvCheckStatisc.DataSource = StatisticsList;
            this.gvCheckStatisc.DataBind();
        }
        #endregion
        /// 
        /// 设计变更统计创建行时激发
        /// 
        /// 
        /// 
        protected void gvCheckStatisc_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string headerStr = "序号#专业#发布数量 本月,累计#业主批准数量 本月,累计#完成情况 本月,累计";
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        #endregion
        #region 合格焊工统计
        #region 绑定GridView
        /// 
        /// 绑定
        /// 
        /// 
        public void PassWelderBindStatisc()
        {
            DateTime startDate = Convert.ToDateTime(this.txtStartDate.Text.Trim());
            DateTime endDate = Convert.ToDateTime(this.txtEndDate.Text.Trim());
            DateTime projectStartDate = Convert.ToDateTime("2015-01-01");
            List StatisticsList = new List();
            Model.Base_Project project = BLL.ProjectService.GetProjectByProjectId(this.CurrUser.LoginProjectId);
            if (project != null)
            {
                if (project.StartDate != null)
                {
                    projectStartDate = Convert.ToDateTime(project.StartDate);
                }
            }
            int i = 1;
            var units = from x in Funs.DB.Project_ProjectUnit
                        join y in Funs.DB.Base_Unit on x.UnitId equals y.UnitId
                        where x.ProjectId == this.CurrUser.LoginProjectId && x.UnitType == BLL.Const.ProjectUnitType_2
                        orderby y.UnitCode
                        select new { x.UnitId, y.UnitName };
            var db = Funs.DB;
            foreach (var item in units)
            {
                var query = from c in db.Comprehensive_InspectionPerson
                            join u in db.Base_Unit on c.UnitId equals u.UnitId into unitJoin
                            from u in unitJoin.DefaultIfEmpty()
                            join cn in db.Base_CNProfessional on c.CNProfessionalId equals cn.CNProfessionalId into cnJoin
                            from cn in cnJoin.DefaultIfEmpty()
                            join p in db.Base_Post on c.PostId equals p.PostId into postJoin
                            from p in postJoin.DefaultIfEmpty()
                            where c.ProjectId == this.CurrUser.LoginProjectId && c.UnitId == item.UnitId
                            select new
                            {
                                c.InspectionPersonId,
                                c.ProjectId,
                                u.UnitId,
                                u.UnitName,
                                c.PersonName,
                                c.ApprovalTime,
                                cn.ProfessionalName,
                                p.PostName
                            };
                //单位下所有集合
                // List totalWelderList = BLL.PersonManageService.GetWelderListByUnitId(this.CurrUser.LoginProjectId, item.UnitId);
                //List welderList = BLL.PersonManageService.GetWelderListByUnitIdAndDate(this.CurrUser.LoginProjectId, item.UnitId, startDate, endDate); 
                var totalWelderList = query.ToList();
                var welderList = query
                    .Where(x => (x.ApprovalTime >= Convert.ToDateTime(startDate) && x.ApprovalTime <= Convert.ToDateTime(endDate)));
                Model.PassWelderStatisc passWelderStatisc = new Model.PassWelderStatisc();
                passWelderStatisc.Num = i;
                passWelderStatisc.UnitName = item.UnitName;
                passWelderStatisc.PipeMountGuard = welderList.Count(x => x.ProfessionalName == "管道" && x.PostName == "焊工");
                passWelderStatisc.PipeTotal = totalWelderList.Count(x => x.ProfessionalName == "管道" && x.PostName == "焊工");
                passWelderStatisc.SteelStructureMountGuard = welderList.Count(x => x.ProfessionalName == "土建" && x.PostName == "焊工");
                passWelderStatisc.SteelStructureTotal = totalWelderList.Count(x => x.ProfessionalName == "土建" && x.PostName == "焊工");
                passWelderStatisc.EquipmentMountGuard = welderList.Count(x => x.ProfessionalName == "设备" && x.PostName == "焊工");
                passWelderStatisc.EquipmentTotal = totalWelderList.Count(x => x.ProfessionalName == "设备" && x.PostName == "焊工");
                passWelderStatisc.OtherMountGuard = welderList.Count(x => x.ProfessionalName != "管道" && x.ProfessionalName != "土建" && x.ProfessionalName != "设备" && x.PostName == "焊工");
                passWelderStatisc.OtherTotal = totalWelderList.Count(x => x.ProfessionalName != "管道" && x.ProfessionalName != "土建" && x.ProfessionalName != "设备" && x.PostName == "焊工");
                StatisticsList.Add(passWelderStatisc);
                i++;
            }
            if (StatisticsList.Count() > 0)//增加总计
            {
                Model.PassWelderStatisc passWelderStatisc = new Model.PassWelderStatisc();
                passWelderStatisc.Num = StatisticsList.Count() + 1;
                passWelderStatisc.UnitName = "合计";
                foreach (Model.PassWelderStatisc item in StatisticsList)
                {
                    passWelderStatisc.PipeMountGuard += item.PipeMountGuard;
                    passWelderStatisc.PipeTotal += item.PipeTotal;
                    passWelderStatisc.SteelStructureMountGuard += item.SteelStructureMountGuard;
                    passWelderStatisc.SteelStructureTotal += item.SteelStructureTotal;
                    passWelderStatisc.EquipmentMountGuard += item.EquipmentMountGuard;
                    passWelderStatisc.EquipmentTotal += item.EquipmentTotal;
                    passWelderStatisc.OtherMountGuard += item.OtherMountGuard;
                    passWelderStatisc.OtherTotal += item.OtherTotal;
                }
                StatisticsList.Add(passWelderStatisc);
            }
            this.gvPassWelder.DataSource = StatisticsList;
            this.gvPassWelder.DataBind();
        }
        #endregion
        /// 
        /// 合格焊工统计
        /// 
        /// 
        /// 
        protected void gvPassWelder_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string headerStr = "序号#分包商#管道焊工 本月上岗,累计#钢结构焊工 本月上岗,累计#设备焊工 本月上岗,累计#其他 本月上岗,累计";
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        #endregion
        #region 施工方案统计
        public void ConstructionStatisticsr()
        {
            var db = Funs.DB;
            DateTime startDate = Convert.ToDateTime(this.txtStartDate.Text.Trim());
            DateTime endDate = Convert.ToDateTime(this.txtEndDate.Text.Trim());
            DateTime projectStartDate = Convert.ToDateTime("2015-01-01");
            Model.Base_Project project = BLL.ProjectService.GetProjectByProjectId(this.CurrUser.LoginProjectId);
            List StatisticsList = new List();
            var unitList = UnitService.GetUnitListByProjectId(this.CurrUser.LoginProjectId).Select(x => x.UnitId).ToList();
            if (project != null)
            {
                if (project.StartDate != null)
                {
                    projectStartDate = Convert.ToDateTime(project.StartDate);
                }
            }
            int i = 1;
            var units = from x in Funs.DB.Project_ProjectUnit
                        join y in Funs.DB.Base_Unit on x.UnitId equals y.UnitId
                        where x.ProjectId == this.CurrUser.LoginProjectId && x.UnitType == BLL.Const.ProjectUnitType_2
                        orderby y.UnitCode
                        select new { x.UnitId, y.UnitName };
            foreach (var item in units)
            {
                var query = from c in db.Solution_CQMSConstructSolution
                            join u in db.Base_Unit on c.UnitId equals u.UnitId into unitJoin
                            from u in unitJoin.DefaultIfEmpty()
                            where c.ProjectId == this.CurrUser.LoginProjectId && c.UnitId == item.UnitId
                            select new
                            {
                                c.ConstructSolutionId,
                                c.ProjectId,
                                u.UnitId,
                                u.UnitName,
                                c.State,
                                c.CompileDate
                            };
                var AllList = query.ToList();
                var unitNCRStatic = query
                    .Where(x => (x.CompileDate >= Convert.ToDateTime(startDate) && x.CompileDate <= Convert.ToDateTime(endDate)));
                Model.CQMSConstructSolutionStatisc NCRStatisc = new Model.CQMSConstructSolutionStatisc();
                NCRStatisc.Num = i;
                NCRStatisc.UnitName = item.UnitName;
                NCRStatisc.CheckNum = unitNCRStatic.Count(x => x.State == "3");
                NCRStatisc.AllNum = AllList.Count();
                StatisticsList.Add(NCRStatisc);
                i++;
            }
            if (StatisticsList.Count() > 0)   //增加总计
            {
                Model.CQMSConstructSolutionStatisc StatisticsLast = new Model.CQMSConstructSolutionStatisc();
                StatisticsLast.Num = StatisticsList.Count() + 1;
                StatisticsLast.UnitName = "合计";
                foreach (Model.CQMSConstructSolutionStatisc item in StatisticsList)
                {
                    StatisticsLast.CheckNum += item.CheckNum;
                    StatisticsLast.AllNum += item.AllNum;
                }
                StatisticsList.Add(StatisticsLast);
            }
            else
            {
                Model.CQMSConstructSolutionStatisc StatisticsLast = new Model.CQMSConstructSolutionStatisc();
                StatisticsLast.Num = 0;
                StatisticsLast.UnitName = "合计";
                StatisticsLast.CheckNum = 0;
                StatisticsLast.AllNum = 0;
                StatisticsList.Add(StatisticsLast);
            }
            //var q = from x in db.Solution_CQMSConstructSolution
            //    join y in units on x.UnitId equals y.UnitId
            //        where x.CompileDate >= Convert.ToDateTime(startDate) && x.CompileDate <= Convert.ToDateTime(endDate) && unitList.Contains(x.UnitId) &&x.ProjectId==this.CurrUser.LoginProjectId
            //        group x by new { x.UnitId, State = x.State == "3", ProjectId = x.ProjectId == project.ProjectId }
            //    into g
            //    select new
            //    {
            //        UnitName=BLL.UnitService.GetUnitNameByUnitId(g.Key.UnitId),
            //        Count = g.Key.UnitId.Count(),
            //    };
            //var total = from x in db.Solution_CQMSConstructSolution
            //     join y in units on x.UnitId equals y.UnitId
            //    where x.CompileDate >= projectStartDate && x.CompileDate <= DateTime.Now && unitList.Contains(x.UnitId) && x.ProjectId == this.CurrUser.LoginProjectId
            //            group x by new { x.UnitId, ProjectId = x.ProjectId == project.ProjectId }
            //    into g
            //    select new
            //    {
            //        UnitName = BLL.UnitService.GetUnitNameByUnitId(g.Key.UnitId),
            //        Count = g.Key.UnitId.Count(),
            //    };
            //var total = from x in units
            //    join y in db.Solution_CQMSConstructSolution on x.UnitId equals y.UnitId into unitJoin
            //    from u in unitJoin.DefaultIfEmpty()
            //    where  u.ProjectId == this.CurrUser.LoginProjectId 
            //    select new
            //    {
            //        UnitName= x.UnitName, 
            //        u.ConstructSolutionId,
            //        u.CompileDate
            //    };
            //var result = total.ToList().Select((item, index) => new
            //{
            //    Index = index + 1,
            //    item.UnitName,
            //    Count = (int)total.ToList().Where(x => x.UnitName == item.UnitName && x.CompileDate >= Convert.ToDateTime(startDate) && x.CompileDate <= Convert.ToDateTime(endDate)).Count(),
            //    AllCount = (int)total.ToList().Where(x => x.UnitName == item.UnitName).Count()
            //});
            //if (result.Count()>0)   //增加总计
            //{
            //    int totalCount = result.Sum(item => item.Count);
            //    int totalAllCount = result.Sum(item => item.AllCount);
            //    result = result.Concat(new[]
            //    {
            //        new
            //        {
            //            Index = result.Count() + 1,
            //            UnitName = "合计",
            //            Count = totalCount,
            //            AllCount= totalAllCount
            //        }
            //    });
            //}
            this.gvConstructionStatistics.DataSource = StatisticsList;
            this.gvConstructionStatistics.DataBind();
        }
        protected void gvConstructionStatistics_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                string headerStr = "序号#报审单位#审批完成数量#总数量";
                DynamicTHeaderHepler dHelper = new DynamicTHeaderHepler();
                dHelper.SplitTableHeader(e.Row, headerStr);
            }
        }
        #endregion
        #region 下月质量控制重点
        /// 
        /// 增加下月质量控制重点
        /// 
        /// 
        /// 
        protected void btnNextQualityControl_Click(object sender, ImageClickEventArgs e)
        {
            nextQualityControlLists.Clear();
            saveNextQualityControl();
            Model.Report_NextQualityControl newNextQualityControl = new Model.Report_NextQualityControl();
            newNextQualityControl.NextQualityControlId = SQLHelper.GetNewID(typeof(Model.Report_NextQualityControl));
            nextQualityControlLists.Add(newNextQualityControl);
            this.gvNextQualityControl.DataSourceID = null;
            this.gvNextQualityControl.DataSource = nextQualityControlLists;
            this.gvNextQualityControl.DataBind();
        }
        /// 
        /// 检查并保存集合
        /// 
        private void saveNextQualityControl()
        {
            nextQualityControlLists.Clear();
            for (int i = 0; i < this.gvNextQualityControl.Rows.Count; i++)
            {
                Model.Report_NextQualityControl newNextQualityControl = new Model.Report_NextQualityControl();
                AspNet.TextBox txtNextQualityControlContent = (AspNet.TextBox)(this.gvNextQualityControl.Rows[i].FindControl("txtNextQualityControlContent"));
                AspNet.Label lblNextQualityControlId = (AspNet.Label)(this.gvNextQualityControl.Rows[i].FindControl("lblNextQualityControlId"));
                newNextQualityControl.NextQualityControlContent = txtNextQualityControlContent.Text.Trim();
                newNextQualityControl.NextQualityControlId = lblNextQualityControlId.Text.Trim();
                nextQualityControlLists.Add(newNextQualityControl);
            }
        }
        /// 
        /// Grid行点击事件
        /// 
        /// 
        /// 
        protected void gvNextQualityControl_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            saveNextQualityControl();
            string nextQualityControlId = e.CommandArgument.ToString();
            if (e.CommandName == "del")
            {
                foreach (Model.Report_NextQualityControl item in nextQualityControlLists)
                {
                    if (item.NextQualityControlId == nextQualityControlId)
                    {
                        nextQualityControlLists.Remove(item);
                        break;
                    }
                }
                this.gvNextQualityControl.DataSourceID = null;
                this.gvNextQualityControl.DataSource = nextQualityControlLists;
                this.gvNextQualityControl.DataBind();
            }
        }
        #endregion
        #region 时间选择事件
        /// 
        /// 开始时间选择事件
        /// 
        /// 
        /// 
        protected void txtStartDate_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txtStartDate.Text.Trim()))
            {
                //CheckLotBindStatisc("CV");//检验批统计:土建
                //CheckLotBindStatisc("EQ");//检验批统计:设备
                //CheckLotBindStatisc("PP");//检验批统计:管道
                //CheckLotBindStatisc("EL");//检验批统计:电气
                //CheckLotBindStatisc("IN");//检验批统计:仪表
                //CheckLotBindStatisc("FF");//检验批统计:反腐
                //CheckLotBindStatisc("XF");//检验批统计:消防
                //GetComprehensive();//综合管理
                //BindStatisc();//无损检测统计
                //NCRBindStatisc();//NCR统计
                //DesignChangeOrderBindStatisc();//设计变更统计
                //PassWelderBindStatisc();//合格焊工统计
                //ConstructionStatisticsr();//施工方案统计
                //Response.AddHeader("Refresh", "0");
                string url = Request.Url.ToString();
                if (url.Contains("?"))
                {
                    url = Request.Url.ToString().Substring(0, Request.Url.ToString().LastIndexOf('?'));
                }
                Response.Redirect(url + "?startdate=" + txtStartDate.Text + "&enddate=" + txtEndDate.Text);
            }
        }
        #endregion
        #region 保存
        /// 
        /// 保存按钮
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            Model.Report_WeekAndMonthReport report = new Model.Report_WeekAndMonthReport();
            report.ProjectId = this.CurrUser.LoginProjectId;
            if (!string.IsNullOrEmpty(this.txtPeriod.Text.Trim()))
            {
                try
                {
                    report.Period = Convert.ToInt32(this.txtPeriod.Text.Trim());
                }
                catch (Exception)
                {
                    ScriptManager.RegisterStartupScript(this, typeof(string), "_alert", "alert('周期输入格式不正确,请重新输入!')", true);
                    return;
                }
            }
            if (!string.IsNullOrEmpty(this.txtStartDate.Text))
            {
                report.StartDate = Convert.ToDateTime(this.txtStartDate.Text);
            }
            if (!string.IsNullOrEmpty(this.txtEndDate.Text))
            {
                report.EndDate = Convert.ToDateTime(this.txtEndDate.Text);
            }
            report.ReportType = "1";
            BLL.ThisWeekOrMonthContentService.DeleteThisWeekOrMonthContentByReportId(this.ReportId);
            BLL.RowMaterialProblemService.DeleteRowMaterialProbleByReportId(this.ReportId);
            BLL.ConstructionProblemsService.DeleteConstructionProblemsByReportId(this.ReportId);
            BLL.NextQualityControlService.DeleteNextQualityControlByReportId(this.ReportId);
            if (!string.IsNullOrEmpty(this.ReportId))
            {
                report.ReportId = this.ReportId;
                BLL.WeekAndMonthReportService.UpdateWeekAndMonthReport(report);
            }
            else
            {
                this.ReportId = SQLHelper.GetNewID(typeof(Model.Report_WeekAndMonthReport));
                report.ReportId = this.ReportId;
                BLL.WeekAndMonthReportService.AddWeekAndMonthReport(report);
            }
            //本月主要工作内容
            saveThisWeekAndMonthContent();
            foreach (var item in thisWeekOrMonthContentLists)
            {
                item.ReportId = report.ReportId;
                BLL.ThisWeekOrMonthContentService.AddThisWeekOrMonthContent(item);
            }
            //原材料问题
            saveRowMaterialProblem();
            foreach (var item in rowMaterialProblemLists)
            {
                item.ReportId = report.ReportId;
                BLL.RowMaterialProblemService.AddRowMaterialProblem(item);
            }
            //施工过程问题
            saveConstructionProblems();
            foreach (var item in constructionProblemsLists)
            {
                item.ReportId = report.ReportId;
                BLL.ConstructionProblemsService.AddConstructionProblems(item);
            }
            // 综合
            BLL.ComprehensiveService.DeleteComprehensiveByReportId(ReportId);
            Model.Report_Comprehensive comprehensive = new Model.Report_Comprehensive();
            comprehensive.ComprehensiveId = SQLHelper.GetNewID(typeof(Model.Report_Comprehensive));
            comprehensive.ReportId = this.ReportId;
            if (this.txt1.Text != string.Empty)
            {
                comprehensive.TotalCount = Convert.ToInt32(this.txt1.Text.Trim());
            }
            comprehensive.EquipmentRate = this.txt4.Text.Trim();
            comprehensive.Others = this.txt9.Text.Trim();
            BLL.ComprehensiveService.AddComprehensive(comprehensive);
            //下月质量控制重点
            saveNextQualityControl();
            foreach (var item in nextQualityControlLists)
            {
                item.ReportId = report.ReportId;
                BLL.NextQualityControlService.AddNextQualityControl(item);
            }
            ShowNotify("保存成功!", MessageBoxIcon.Success);
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            //ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "");
        }
        #endregion
        #region 打印
        /// 
        /// 打印按钮
        /// 
        /// 
        /// 
        protected void btnPrint_Click(object sender, ImageClickEventArgs e)
        {
            if (!string.IsNullOrEmpty(ReportId))
            {
                ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "");
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, typeof(string), "_alert", "alert('请先保存后再打印!')", true);
                return;
            }
        }
        #endregion
    }
}