using BLL;
using FineUIPro.Web.Controls;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using AspNet = System.Web.UI.WebControls;
namespace FineUIPro.Web.HJGL.WeldingReport
{
    public partial class OneDayReport : PageBase
    {
        #region 加载
        /// 
        /// 加载页面
        /// 
        /// 
        /// 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Funs.DropDownPageSize(this.ddlPageSize);
                this.ddlPageSize.SelectedValue = this.Grid1.PageSize.ToString();
                List units = new List();
                dpDate.SelectedDate = new DateTime( DateTime.Now.Year, DateTime.Now.Month,1);
                var pUnit = BLL.ProjectUnitService.GetProjectUnitByUnitIdProjectId(this.CurrUser.LoginProjectId, this.CurrUser.UnitId);
                if (pUnit == null || pUnit.UnitType == Const.ProjectUnitType_1)
                {
                    units = BLL.UnitService.GetUnitByProjectIdUnitTypeList(this.CurrUser.LoginProjectId, BLL.Const.ProjectUnitType_2);
                    //this.drpUnit.Enabled = false;
                    this.drpUnit.DataTextField = "UnitName";
                    this.drpUnit.DataValueField = "UnitId";
                    this.drpUnit.DataSource = units;
                    this.drpUnit.DataBind();
                    Funs.FineUIPleaseSelect(this.drpUnit);           
                 }
                else
                {
                    units = BLL.UnitService.GetSubUnitsListBySupervisorUnitId(this.CurrUser.ProjectId, this.CurrUser.UnitId);
                    this.drpUnit.Enabled = false;
                    this.drpUnit.DataTextField = "UnitName";
                    this.drpUnit.DataValueField = "UnitId";
                    this.drpUnit.DataSource = units;
                    this.drpUnit.DataBind();
                    this.drpUnit.SelectedValue = CurrUser.UnitId; 
                }
                //显示列
                //Model.Sys_UserShowColumns c = BLL.UserShowColumnsService.GetColumnsByUserId(this.CurrUser.UserId, Const.UnitAreaQualityMenuId);
                //if (c != null)
                //{
                //    this.GetShowColumn(c.Columns);
                //}
                //BindGrid();
            }
        }
        #endregion
        #region 绑定BindGrid
        /// 
        /// 
        /// 
        private DataTable tb = null;
        /// 
        /// 绑定数据
        /// 
        private void BindGrid()
        {
            string strSql = @"SELECT 0 id, WorkArea.WorkAreaId, WorkArea.WorkAreaCode   ,--工区代号
		                            WorkArea.WorkAreaName  ,--工区代号		
		                            CAST(ISNULL(total_jot.total_din,0) AS DECIMAL(19,2)) AS total_din ,--总达因	
                                    finished_total_din,
                                    '' Type,0 has_din,0 res_din, '' has_per, '' HSData
                            FROM ProjectData_WorkArea AS  WorkArea 
                            LEFT JOIN (SELECT COUNT(*) total_jot ,pw_isoinfo.WorkAreaId ,
                                        SUM( case when pw_isoinfo.[Is_Standard] = 0 then JOT_Size when  pw_jointinfo.Extend_Length!='' then  pw_jointinfo.Extend_Length else 0 end) AS total_din
			                            ,SUM(JOT_DoneDin) AS finished_total_din
			                            FROM pw_jointinfo 
			                            LEFT JOIN pw_isoinfo  ON pw_jointinfo.ISO_ID = pw_isoinfo.ISO_ID
			                            LEFT JOIN Base_Material ON Base_Material.MaterialId = pw_jointinfo.MaterialId
			                            WHERE  (pw_isoinfo.Is_Standard=@IsStandard OR @IsStandard ='') and pw_isoinfo.ProjectId = @ProjectId
			                            GROUP BY pw_isoinfo.WorkAreaId)	AS total_jot ON total_jot.WorkAreaId = WorkArea.WorkAreaId 
                            WHERE   ";
            List listStr = new List();
            strSql += " WorkArea.ProjectId = @ProjectId";
            listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            if (this.drpUnit.SelectedValue != BLL.Const._Null)
            { strSql += " and WorkArea.UnitId = @UnitId";
                listStr.Add(new SqlParameter("@UnitId", this.drpUnit.SelectedValue));
            }
            if (this.cb_IsStandard.SelectedIndexArray != null && this.cb_IsStandard.SelectedIndexArray.Length == 1)
            {
                listStr.Add(new SqlParameter("@IsStandard", this.cb_IsStandard.SelectedValueArray[0]));
            }
            else
            {
                listStr.Add(new SqlParameter("@IsStandard", ""));
            }
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb1 = SQLHelper.GetDataTableRunText(strSql, parameter);
            strSql = @"  select   WorkAreaId,[day],[month],COUNT(distinct JOT_CellWelder)  as WelderNum from (SELECT DAY(jot_welddate) as [day],MONTH(jot_welddate) as [month], 
		                        pw_isoinfo.WorkAreaId ,JOT_CellWelder  
		                        FROM pw_jointinfo 
		                        LEFT JOIN pw_isoinfo  ON pw_jointinfo.ISO_ID = pw_isoinfo.ISO_ID
		                        LEFT JOIN Base_Material ON Base_Material.MaterialId = pw_jointinfo.MaterialId
		                        LEFT JOIN BO_WeldReportMain ON BO_WeldReportMain.dreportid = pw_jointinfo.dreportid 
		                        WHERE  (pw_isoinfo.Is_Standard=@IsStandard OR @IsStandard ='' )  and  pw_isoinfo.ProjectId = '" + this.CurrUser.LoginProjectId + "' ";
            if (this.drpUnit.SelectedValue != BLL.Const._Null)
            {
                strSql += " and pw_isoinfo.UnitId ='" + this.drpUnit.SelectedValue + "' ";
            }
            strSql += " and jot_welddate >='" + dpDate.SelectedDate.Value.ToString("yyyy-MM-dd") + "' and jot_welddate <'" + dpDate.SelectedDate.Value.AddMonths(1).ToString("yyyy-MM-dd") + "'" +
              @"union   
                        SELECT DAY(jot_welddate) as [day],MONTH(jot_welddate) as [month], 
		                        pw_isoinfo.WorkAreaId ,JOT_FloorWelder  
		                        FROM pw_jointinfo 
		                        LEFT JOIN pw_isoinfo  ON pw_jointinfo.ISO_ID = pw_isoinfo.ISO_ID
		                        LEFT JOIN Base_Material ON Base_Material.MaterialId = pw_jointinfo.MaterialId
		                        LEFT JOIN BO_WeldReportMain ON BO_WeldReportMain.dreportid = pw_jointinfo.dreportid 
		                        WHERE (pw_isoinfo.Is_Standard=@IsStandard OR @IsStandard = '') and  pw_isoinfo.ProjectId = '" + this.CurrUser.LoginProjectId + "'";
            if (this.drpUnit.SelectedValue != BLL.Const._Null)
            {
                strSql += "and pw_isoinfo.UnitId ='" + this.drpUnit.SelectedValue + "' ";
            }
            strSql += "  and jot_welddate >='" + dpDate.SelectedDate.Value.ToString("yyyy-MM-dd") + "' and jot_welddate <'" + dpDate.SelectedDate.Value.AddMonths(1).ToString("yyyy-MM-dd") + "'" +
                                @") as a  group by WorkAreaId,[day],[month]";
            listStr = new List();
            //strSql += " WorkArea.ProjectId = @ProjectId";
            //listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            //strSql += " and WorkArea.UnitId = @UnitId";
            //listStr.Add(new SqlParameter("@UnitId", this.drpUnit.SelectedValue)); 
            if (this.cb_IsStandard.SelectedIndexArray != null && this.cb_IsStandard.SelectedIndexArray.Length == 1)
            {
                listStr.Add(new SqlParameter("@IsStandard", this.cb_IsStandard.SelectedValueArray[0]));
            }
            else
            {
                listStr.Add(new SqlParameter("@IsStandard", ""));
            }
            parameter = listStr.ToArray();
            DataTable tb2 = SQLHelper.GetDataTableRunText(strSql, parameter);
            strSql = @"  SELECT DAY(jot_welddate) as [day],MONTH(jot_welddate) as [month],
                             COUNT(*) finished_total_jot_bq ,
                             pw_isoinfo.WorkAreaId ,SUM(
                             case when pw_isoinfo.[Is_Standard] = 0 then JOT_DoneDin when  pw_jointinfo.Extend_Length !='' then   pw_jointinfo.Extend_Length else 0 end 
                             ) AS finished_total_din_bq	 
			                            FROM pw_jointinfo 
			                            LEFT JOIN pw_isoinfo  ON pw_jointinfo.ISO_ID = pw_isoinfo.ISO_ID
			                            LEFT JOIN Base_Material ON Base_Material.MaterialId = pw_jointinfo.MaterialId
			                            LEFT JOIN BO_WeldReportMain ON BO_WeldReportMain.dreportid = pw_jointinfo.dreportid 
			                             WHERE (pw_isoinfo.Is_Standard=@IsStandard OR @IsStandard ='') and  pw_isoinfo.ProjectId = '" + this.CurrUser.LoginProjectId + "'";
            if (this.drpUnit.SelectedValue != BLL.Const._Null)
            {
                strSql += "and pw_isoinfo.UnitId ='" + this.drpUnit.SelectedValue + "'";
            }
            strSql += "  and jot_welddate >='" + dpDate.SelectedDate.Value.ToString("yyyy-MM-dd") + "' and jot_welddate <'" + dpDate.SelectedDate.Value.AddMonths(1).ToString("yyyy-MM-dd") + "'" +
                                        @"GROUP BY pw_isoinfo.WorkAreaId,DAY(jot_welddate),MONTH(jot_welddate) ";
            listStr = new List();
            //strSql += " WorkArea.ProjectId = @ProjectId";
            //listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            //strSql += " and WorkArea.UnitId = @UnitId";
            //listStr.Add(new SqlParameter("@UnitId", this.drpUnit.SelectedValue)); 
            if (this.cb_IsStandard.SelectedIndexArray != null && this.cb_IsStandard.SelectedIndexArray.Length == 1)
            {
                listStr.Add(new SqlParameter("@IsStandard", this.cb_IsStandard.SelectedValueArray[0]));
            }
            else
            {
                listStr.Add(new SqlParameter("@IsStandard", ""));
            }
            parameter = listStr.ToArray();
            DataTable tb3 = SQLHelper.GetDataTableRunText(strSql, parameter);
            strSql = @"  SELECT  COUNT(*) finished_total_jot_bq ,
                             pw_isoinfo.WorkAreaId ,SUM(
                             case when pw_isoinfo.[Is_Standard] = 0 then JOT_DoneDin when  pw_jointinfo.Extend_Length !='' then   pw_jointinfo.Extend_Length else 0 end 
                             ) AS finished_total_din_bq	 
			                            FROM pw_jointinfo 
			                            LEFT JOIN pw_isoinfo  ON pw_jointinfo.ISO_ID = pw_isoinfo.ISO_ID
			                            LEFT JOIN Base_Material ON Base_Material.MaterialId = pw_jointinfo.MaterialId
			                            LEFT JOIN BO_WeldReportMain ON BO_WeldReportMain.dreportid = pw_jointinfo.dreportid 
			                             WHERE (pw_isoinfo.Is_Standard=@IsStandard OR @IsStandard ='') and  pw_isoinfo.ProjectId = '" + this.CurrUser.LoginProjectId + "'";
            if (this.drpUnit.SelectedValue != BLL.Const._Null)
            {
                strSql += " and pw_isoinfo.UnitId ='" + this.drpUnit.SelectedValue + "' ";
            }
            strSql += "and  jot_welddate <'" + dpDate.SelectedDate.Value.AddMonths(1).ToString("yyyy-MM-dd") + "' " +
                                        @"GROUP BY pw_isoinfo.WorkAreaId ";
            
            listStr = new List();
            //strSql += " WorkArea.ProjectId = @ProjectId";
            //listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            //strSql += " and WorkArea.UnitId = @UnitId";
            //listStr.Add(new SqlParameter("@UnitId", this.drpUnit.SelectedValue)); 
            if (this.cb_IsStandard.SelectedIndexArray != null && this.cb_IsStandard.SelectedIndexArray.Length == 1)
            {
                listStr.Add(new SqlParameter("@IsStandard", this.cb_IsStandard.SelectedValueArray[0]));
            }
            else
            {
                listStr.Add(new SqlParameter("@IsStandard", ""));
            }
            parameter = listStr.ToArray();
            DataTable tb4 = SQLHelper.GetDataTableRunText(strSql, parameter);
            int day = DateTime.DaysInMonth(dpDate.SelectedDate.Value.Year, dpDate.SelectedDate.Value.Month);
            if (tb1 != null)
            {
                tb1.Columns.Add("has_month_din");
                for (int i = 1; i <= day; i++)
                {
                    tb1.Columns.Add("Day" + i);
                }
            }
            int numCount = tb1.Rows.Count;
            for (int j = numCount - 1; j >= 0; j--)
            {
                var row1 = tb1.NewRow();
                row1[0] = tb1.Rows[j][0];
                row1[1] = tb1.Rows[j][1] + "|n";
                row1[2] = tb1.Rows[j][2];
                row1[3] = tb1.Rows[j][3];
                row1[4] = tb1.Rows[j][4];
                row1[5] = tb1.Rows[j][5];
                tb1.Rows.InsertAt(row1, j + 1);
            }
            for (int j = 0; j < numCount; j++)
            {
                var row1 = tb1.Rows[j * 2];
                row1["id"] = j * 2;
                row1["Type"] = "焊工(人)";
                for (int i = 0; i < tb2.Rows.Count; i++)
                {
                    var row2 = tb2.Rows[i];
                    if (row2["WorkAreaId"].ToString() == row1["WorkAreaId"].ToString())
                    {
                        if (tb1.Columns.Contains("Day" + row2["day"]))
                        {
                            row1["Day" + row2["day"]] = row2["WelderNum"];
                        }
                    }
                }
                row1 = tb1.Rows[j * 2 + 1];
                row1["id"] = j * 2 + 1;
                row1["Type"] = "工作量(吋)";
                for (int i = 0; i < tb3.Rows.Count; i++)
                {
                    var row3 = tb3.Rows[i];
                    if (row3["WorkAreaId"].ToString() + "|n" == row1["WorkAreaId"].ToString())
                    {
                        if (tb1.Columns.Contains("Day" + row3["day"]) && row3["finished_total_din_bq"] != DBNull.Value)
                        {
                            try
                            {
                                row1["Day" + row3["day"]] = ((decimal)row3["finished_total_din_bq"]).ToString("#0.##");
                            }
                            catch (Exception e) { }
                        }
                    }
                }
                double has = 0;
                var row4 = tb1.Rows[j * 2 + 1];
                for (int i = 1; i <= day; i++)
                {
                    if (row4["Day" + i] != DBNull.Value)
                        try
                        {
                            has += double.Parse(row4["Day" + i].ToString());
                        }
                        catch (Exception e) { }
                }
                tb1.Rows[j * 2]["has_month_din"] = has;
                double hasTotalfinsh = 0;
                for(int i=0;i 0.000000001)
                        {
                            tb1.Rows[j * 2]["HSData"] = (100 * hasTotalfinsh / double.Parse(row4["total_din"].ToString())).ToString("#0.##") + "%";
                            tb1.Rows[j * 2]["finished_total_din"] = hasTotalfinsh;
                        }
                    }
                    catch (Exception e) { }
                }
            }
            var rowTotal1 = tb1.NewRow();
            rowTotal1[0] = "10000000";
            rowTotal1[1] = "";
            rowTotal1[2] = "";
            rowTotal1[3] = "合计";
            rowTotal1["Type"] = "焊工(人)";
            var rowTotal2 = tb1.NewRow();
            rowTotal2[0] = "10000001";
            rowTotal2[1] = "";
            rowTotal2[2] = "";
            rowTotal2[3] = "";
            rowTotal2["Type"] = "工作量(吋)";
            double total_din = 0;
            for (int j = 0; j < numCount; j++)
            {
                try
                {
                    total_din += double.Parse(tb1.Rows[j * 2 + 1]["total_din"].ToString());
                }
                catch (Exception e)
                {
                }
                for (int i = 1; i <= day; i++)
                {
                    double temp1 = 0;
                    double temp2 = 0;
                    double.TryParse(rowTotal1["Day" + i] != DBNull.Value ? rowTotal1["Day" + i].ToString() : "0", out temp1);
                    double.TryParse(tb1.Rows[j * 2]["Day" + i] != DBNull.Value ? tb1.Rows[j * 2]["Day" + i].ToString() : "0", out temp2);
                    rowTotal1["Day" + i] = temp1 + temp2;
                    double temp3 = 0;
                    double temp4 = 0;
                    double.TryParse(rowTotal2["Day" + i] != DBNull.Value ? rowTotal2["Day" + i].ToString() : "0", out temp3);
                    double.TryParse(tb1.Rows[j * 2 + 1]["Day" + i] != DBNull.Value ? tb1.Rows[j * 2 + 1]["Day" + i].ToString() : "0", out temp4);
                    rowTotal2["Day" + i] = temp3 + temp4;
                }
            }
            tb1.Rows.Add(rowTotal1);
            tb1.Rows.Add(rowTotal2);
           
            double hasTotal = 0;
            for (int i = 1; i <= day; i++)
            {
                if (rowTotal2["Day" + i] != DBNull.Value)
                    try
                    {
                        hasTotal += double.Parse(rowTotal2["Day" + i].ToString());
                    }
                    catch (Exception e)
                    {
                    }
            }
            rowTotal1["has_month_din"] = hasTotal;
            hasTotal = 0;
            for (int i = 0; i < tb4.Rows.Count; i++)
            {
                double hasTotalfinsh = 0;
                var row44 = tb4.Rows[i];
                double.TryParse(row44["finished_total_din_bq"].ToString(), out hasTotalfinsh);
                hasTotal += hasTotalfinsh;
            }
            rowTotal2["total_din"] = total_din;
            rowTotal1["total_din"] = total_din;
            rowTotal1["finished_total_din"] = hasTotal; 
            try
            {
                rowTotal1["res_din"] = double.Parse(rowTotal2["total_din"].ToString()) - hasTotal;
                if (double.Parse(rowTotal2["total_din"].ToString()) > 0.000000001)
                {
                    rowTotal1["HSData"] = (100 * hasTotal / double.Parse(rowTotal2["total_din"].ToString())).ToString("#0.##") + "%";
                    rowTotal1["finished_total_din"] = hasTotal;
                }
            }
            catch (Exception e)
            {
            }
            Grid1.RecordCount = tb1.Rows.Count;
            Grid1.DataSource = tb1;
            Grid1.DataBind();
        }
        /// 
        /// 改变索引事件
        /// 
        /// 
        /// 
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            BindGrid();
        }
        /// 
        /// 分页下拉选择事件
        /// 
        /// 
        /// 
        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid1.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
            BindGrid();
        }
        /// 
        /// 排序
        /// 
        /// 
        /// 
        protected void Grid1_Sort(object sender, FineUIPro.GridSortEventArgs e)
        {
            this.BindGrid();
        }
        #endregion
      
       
        /// 
        /// 
        /// 
        /// 
        /// 
        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            this.BindGrid();
            // 显示列
            //var c = UserShowColumnsService.GetColumnsByUserId(this.CurrUser.UserId, Const.UnitAreaQualityMenuId);
            //if (c != null)
            //{
            //    this.GetShowColumn(c.Columns);
            //}
        }
        /// 
        /// 显示的列
        /// 
        /// 
        private void GetShowColumn(string column)
        {
            if (!string.IsNullOrEmpty(column))
            {
                for (int i = 0; i < Grid1.Columns.Count; i++)
                {
                    this.Grid1.Columns[i].Hidden = true;
                }
                List columns = column.Split(',').ToList();
                foreach (var item in columns)
                {
                    this.Grid1.Columns[Convert.ToInt32(item)].Hidden = false;
                }
            }
        }
        #region 统计按钮事件
        /// 
        /// 统计
        /// 
        /// 
        /// 
        protected void BtnAnalyse_Click(object sender, EventArgs e)
        {
            if (drpUnit.SelectedValue != BLL.Const._Null)
            {
                ColumnUnitName.HeaderText = drpUnit.SelectedText;
            }
            if (dpDate.SelectedDate.HasValue)
            {
                CollumMonth.HeaderText = dpDate.SelectedDate.Value.ToString("yyyy年MM月");
                int day = DateTime.DaysInMonth(dpDate.SelectedDate.Value.Year, dpDate.SelectedDate.Value.Month);
                if (day == 30)
                {
                    Day31.Hidden = true;
                }
                else if (day == 29)
                {
                    Day30.Hidden = true;
                    Day31.Hidden = true;
                }
                else if (day == 28)
                {
                    Day29.Hidden = true;
                    Day30.Hidden = true;
                    Day31.Hidden = true;
                }
            }
            else
            {
                Alert.ShowInTop("请选择日期!", MessageBoxIcon.Warning);
                return;
            }
            BindGrid();
            //OutputSummaryData();
        }
        #endregion
        #region 导出按钮
        /// 导出按钮
        /// 
        /// 
        /// 
        protected void btnOut_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            string filename = Funs.GetNewFileName();
            Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode("储罐/管道每日焊接量统计表" + filename, System.Text.Encoding.UTF8) + ".xls");
            Response.ContentType = "application/excel";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.Write(GetGridTableHtml(Grid1));
            Response.End();
        }
        /// 
        /// 导出方法
        /// 
        /// 
        /// 
        private string GetGridTableHtml(Grid grid)
        {
            StringBuilder sb = new StringBuilder();
            MultiHeaderTable mht = new MultiHeaderTable();
            mht.ResolveMultiHeaderTable(Grid1.Columns);
            sb.Append("");
            sb.Append("");
            foreach (List
");
            return sb.ToString();
        }
        #endregion
        #region 下拉选择事件
        /// 
        /// 单位下拉选择事件
        /// 
        ///  param >
        /// < param name="e">
        protected void drpUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }
        #endregion
        protected void cb_IsStandard_SelectedIndexChanged(object sender, EventArgs e)
        {
        }
    }
}