using BLL;
using Model;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace FineUIPro.Web.HJGL.WeldingReport
{
    public partial class NDTWeekReport : PageBase
    {
        #region 定义变量
        /// 
        /// 主键
        /// 
        public string NDTReportId
        {
            get
            {
                return (string)ViewState["NDTReportId"];
            }
            set
            {
                ViewState["NDTReportId"] = value;
            }
        }
        #endregion
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }
        private void BindGrid()
        {
            List list = new List();
            List NDTReportLists = BLL.NDTReportService.GetNDTReportByProjectId(this.CurrUser.LoginProjectId, "1");
            foreach (var item in NDTReportLists)
            {
                SpRpNDTWeekReport t = new SpRpNDTWeekReport();
                t.NDTReportId = item.NDTReportId;
                t.ProjectId = item.ProjectId;
                t.ProjectName = BLL.ProjectService.GetProjectNameByProjectId(item.ProjectId);
                t.StaDate = string.Format("{0:yyyy-MM-dd}", item.StartDate) + "至" + string.Format("{0:yyyy-MM-dd}", item.EndDate);
                list.Add(t);
            }
            this.Grid1.DataSource = list;
            this.Grid1.DataBind();
        }
        #endregion
        #region 查询
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string projectName = BLL.ProjectService.GetProjectByProjectId(this.CurrUser.LoginProjectId).ProjectName;
            if (!string.IsNullOrEmpty(this.txtStartDate.Text) && !string.IsNullOrEmpty(this.txtEndDate.Text))
            {
                string staDate = this.txtStartDate.Text + "至" + this.txtEndDate.Text;
                SpRpNDTWeekReport t = new SpRpNDTWeekReport();
                this.NDTReportId = SQLHelper.GetNewID(typeof(Model.NDTReport));
                t.NDTReportId = this.NDTReportId;
                t.ProjectId = this.CurrUser.LoginProjectId;
                t.ProjectName = projectName;
                t.StaDate = staDate;
                List list = new List();
                list.Add(t);
                Grid1.DataSource = list;
                Grid1.DataBind();
            }
            else
            {
                Alert.ShowInTop("日期不能为空!", MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion
        #region 保存
        /// 
        /// 保存
        /// 
        /// 
        /// 
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txtStartDate.Text) && !string.IsNullOrEmpty(this.txtEndDate.Text))
            {
                Model.NDTReport ndtReport = new Model.NDTReport();
                ndtReport.NDTReportId = this.NDTReportId;
                ndtReport.ProjectId = this.CurrUser.LoginProjectId;
                ndtReport.StartDate = Funs.GetNewDateTime(this.txtStartDate.Text.Trim());
                ndtReport.EndDate = Funs.GetNewDateTime(this.txtEndDate.Text.Trim());
                ndtReport.RType = "1";
                BLL.NDTReportService.AddNDTReort(ndtReport);
                ShowNotify("保存成功!", MessageBoxIcon.Success);
                BindGrid();
                this.txtStartDate.Text = string.Empty;
                this.txtEndDate.Text = string.Empty;
            }
            else
            {
                Alert.ShowInTop("日期不能为空!", MessageBoxIcon.Warning);
                return;
            }
        }
        #endregion
        #region 右键删除
        /// 
        /// 右键删除
        /// 
        /// 
        /// 
        protected void btnMenuDelete_Click(object sender, EventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length > 0)
            {
                foreach (int rowIndex in Grid1.SelectedRowIndexArray)
                {
                    string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                    var rep = BLL.NDTReportService.GetNDTReportById(rowID);
                    if (rep != null)
                    {
                        BLL.NDTReportService.DeleteNDTReportById(rowID);
                    }
                }
                ShowNotify("删除成功!", MessageBoxIcon.Success);
                BindGrid();
            }
        }
        #endregion
        #region 日期选择事件
        /// 
        /// 开始日期选择事件
        /// 
        /// 
        /// 
        protected void txtStartDate_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txtStartDate.Text.Trim()))
            {
                this.txtEndDate.Text = Funs.GetNewDateTime(this.txtStartDate.Text.Trim()).Value.AddDays(6).ToShortDateString();
            }
        }
        /// 
        /// 结束日期选择事件
        /// 
        /// 
        /// 
        protected void txtEndDate_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txtEndDate.Text.Trim()))
            {
                this.txtStartDate.Text = Funs.GetNewDateTime(this.txtEndDate.Text.Trim()).Value.AddDays(-6).ToShortDateString();
            }
        }
        #endregion
        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            object[] keys = Grid1.DataKeys[e.RowIndex];
            string fileId = string.Empty;
            if (keys == null)
            {
                return;
            }
            else
            {
                fileId = keys[0].ToString();
            }
            if (e.CommandName == "print")
            {
                var projectName = ProjectService.GetProjectNameByProjectId(CurrUser.LoginProjectId);
                string dateStr = Grid1.Rows[e.RowIndex].Values[2].ToString();
                Dictionary keyValuePairs = new Dictionary();
                keyValuePairs.Add("projectName", projectName);
                keyValuePairs.Add("dateStr", dateStr);
                List units = UnitService.GetUnitByProjectIdUnitTypeList(this.CurrUser.LoginProjectId, Const.ProjectUnitType_5);
                string unitName = "";
                foreach (Base_Unit unit in units)
                {
                    unitName += unit.UnitName + ",";
                }
                keyValuePairs.Add("unitName", unitName);
                BLL.Common.FastReportService.ResetData();
                BLL.Common.FastReportService.AddFastreportParameter(keyValuePairs);
                var dates = dateStr.Split('至');
                DateTime begin = DateTime.Parse(dates[0]);
                DateTime end = DateTime.Parse(dates[1]);
                string strSql1 = @"select unit.UnitId,unit.UnitName,workArea.WorkAreaName,workArea.WorkAreaCode,curr.curr_pass_film,curr.curr_total_film,recurr.recurr_pass_film,recurr.recurr_total_film, 0.0 curr_pass_rate,0.0 recurr_pass_rate
,curr_trust_point.curr_trust_count_total, currpoint.curr_point_count_total, currpoint.curr_pass_point ,0.0 curr_pass_rate_point                                       
from Base_Unit unit right join  
	                                             ProjectData_WorkArea workArea on workArea.UnitId=unit.UnitId
	                                             left join
		                                            ( SELECT WorkAreaId,IsoInfo.UnitId,COUNT(*) AS curr_check_count_total
                                                        , SUM(cht_totalfilm) AS  curr_total_film
                                                    , SUM(cht_passfilm) AS curr_pass_film                                             
                                                    FROM  CH_Check Checks                                                 
                                                    LEFT JOIN CH_CheckItem ON ch_checkitem.CHT_CheckID = Checks.CHT_CheckID
		                                            LEFT JOIN PW_JointInfo as JointInfo ON JointInfo.JOT_ID = ch_checkitem.JOT_ID
		                                            LEFT JOIN PW_IsoInfo as IsoInfo ON IsoInfo.ISO_ID = JointInfo.ISO_ID 
		                                            where JointInfo.ProjectId=@ProjectId    and (cht_checkdate >= @date1 OR @date1 IS NULL) and(cht_checkdate <= @date2 OR @date2 IS NULL)
		                                            group by WorkAreaId,IsoInfo.UnitId) as curr on unit.UnitId= curr.UnitId and workArea.WorkAreaId=curr.WorkAreaId		                                            
	                                            left join
                                            ( SELECT WorkAreaId,IsoInfo.UnitId,COUNT(*) AS recurr_check_count_total
                                                        , SUM(cht_totalfilm) AS  recurr_total_film
                                                    , SUM(cht_passfilm) AS recurr_pass_film                                             
                                                    FROM  CH_Check Checks                                                 
                                                    LEFT JOIN CH_CheckItem ON ch_checkitem.CHT_CheckID = Checks.CHT_CheckID
		                                            LEFT JOIN PW_JointInfo as JointInfo ON JointInfo.JOT_ID = ch_checkitem.JOT_ID
		                                            LEFT JOIN PW_IsoInfo as IsoInfo ON IsoInfo.ISO_ID = JointInfo.ISO_ID 
		                                            LEFT JOIN CH_Trust  trust on trust.CH_TrustID = Checks.CH_TrustID
		                                            where JointInfo.ProjectId=@ProjectId  and  trust.CH_TrustType='2'   and (cht_checkdate >= @date1 OR @date1 IS NULL) and(cht_checkdate <= @date2 OR @date2 IS NULL)
		                                            group by WorkAreaId,IsoInfo.UnitId) as recurr on unit.UnitId= recurr.UnitId and workArea.WorkAreaId=recurr.WorkAreaId
	                                             
                                               left join
		                                            ( SELECT WorkAreaId,IsoInfo.UnitId,COUNT(*) AS curr_point_count_total
                                                       , SUM(case when CHT_CheckResult='合格' then 1 else 0 end) AS  curr_pass_point   
                                                    FROM  CH_Check Checks                                                 
                                                    LEFT JOIN CH_CheckItem ON ch_checkitem.CHT_CheckID = Checks.CHT_CheckID
		                                            LEFT JOIN PW_JointInfo as JointInfo ON JointInfo.JOT_ID = ch_checkitem.JOT_ID
		                                            LEFT JOIN PW_IsoInfo as IsoInfo ON IsoInfo.ISO_ID = JointInfo.ISO_ID 
		                                            where JointInfo.ProjectId=@ProjectId    and (cht_checkdate >= @date1 OR @date1 IS NULL) and(cht_checkdate <= @date2 OR @date2 IS NULL)
		                                            group by WorkAreaId,IsoInfo.UnitId) as currpoint on unit.UnitId= currpoint.UnitId and workArea.WorkAreaId=currpoint.WorkAreaId		   
                                               left join (
                                                    SELECT WorkAreaId,IsoInfo.UnitId,COUNT(*) AS curr_trust_count_total                                             
                                                            FROM  CH_Trust trust                                                 
                                                            LEFT JOIN CH_TrustItem  trustitem ON trustitem .CH_TrustID = trust.CH_TrustID
		                                                    LEFT JOIN PW_JointInfo as JointInfo ON JointInfo.JOT_ID = trustitem.JOT_ID
		                                                    LEFT JOIN PW_IsoInfo as IsoInfo ON IsoInfo.ISO_ID = JointInfo.ISO_ID 
		                                                    where   JointInfo.ProjectId=@ProjectId    and (trust.CH_TrustDate >= @date1 OR @date1 IS NULL) and(trust.CH_TrustDate <= @date2 OR @date2 IS NULL)  
		                                                    group by WorkAreaId,IsoInfo.UnitId) as curr_trust_point on unit.UnitId= curr_trust_point.UnitId and workArea.WorkAreaId=curr_trust_point.WorkAreaId
                                            where workArea.ProjectId=@ProjectId                                                ";
                List listpar = new List
                {
                    new SqlParameter("@projectId", this.CurrUser.LoginProjectId)
                };
                listpar.Add(new SqlParameter("@date1", begin.ToString("yyyy-MM-dd")));
                listpar.Add(new SqlParameter("@date2", end.ToString("yyyy-MM-dd")));
                SqlParameter[] parameter5 = listpar.ToArray();
                DataTable dt = SQLHelper.GetDataTableRunText(strSql1, parameter5);
                if (dt != null)
                {
                    dt.TableName = "Table1";
                    foreach (DataRow row in dt.Rows)
                    {
                        try
                        {
                          
                            row["curr_pass_rate"] =1.0 * int.Parse(row["curr_pass_film"].ToString()) / int.Parse(row["curr_total_film"].ToString());
                        }
                        catch (Exception e1)
                        { }
                        try
                        {
                            row["recurr_pass_rate"] = 1.0 * int.Parse(row["recurr_pass_film"].ToString()) / int.Parse(row["recurr_total_film"].ToString());
                        }
                        catch (Exception e2)
                        { }
                        try
                        {
                            row["curr_pass_rate_point"] = 1.0 * int.Parse(row["curr_pass_point"].ToString()) / int.Parse(row["curr_point_count_total"].ToString());
                        }
                        catch (Exception e3)
                        { }
                    }
                }
                BLL.Common.FastReportService.AddFastreportTable(dt);
                string initTemplatePath = "";
                string rootPath = Server.MapPath("~/");
                initTemplatePath = "File\\Fastreport\\无损检测周报.frx";
                if (File.Exists(rootPath + initTemplatePath))
                {
                    PageContext.RegisterStartupScript(Window2.GetShowReference(String.Format("../TrustManage/Fastreport.aspx?ReportPath={0}", rootPath + initTemplatePath)));
                }
            }
        }
    }
}