using BLL;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FineUIPro.Web.Transfer.Chart
{
    public partial class SystemStatusSummary : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid1();
            }
        }
        /// 
        /// 查询
        /// 
        /// 
        /// 
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid1();
        }
        /// 
        /// 查询绑定数据
        /// 
        public void BindGrid1()
        {
            List listStr = new List();
            //计算本周日期段
            DateTime today = DateTime.Today;
            int dayOfWeek = (int)today.DayOfWeek;
            DateTime startWeebTime = Convert.ToDateTime(today.AddDays(-dayOfWeek + 1).ToString("yyyy-MM-dd") + " 00:00:00");
            DateTime endWeebTime = Convert.ToDateTime(today.AddDays(-dayOfWeek + 7).ToString("yyyy-MM-dd") + " 23:59:59");
            StringBuilder strSql = new StringBuilder("");
            strSql.AppendLine(" IF OBJECT_ID('tempdb..#AllLHCSystemListTemp') IS NOT NULL drop table #AllLHCSystemListTemp; ");
            strSql.AppendLine("  IF OBJECT_ID('tempdb..#LHCSystemListTemp') IS NOT NULL drop table #LHCSystemListTemp; ");
            strSql.AppendLine("  select * INTO #AllLHCSystemListTemp from Transfer_LHCSystemList(NOLOCK) where ProjectId =@ProjectId; ");
            strSql.AppendLine("  select isnull([Type],'0') [Type],(CASE isnull([Type],'0') WHEN '1' THEN 'Non Process system' ELSE 'Process System' END) Category,count(1) System_Qty ");
            strSql.AppendLine(",cast(0 as decimal(18,2)) Cumulative_Plan,cast(0 as decimal(18,2)) Cumulative_Actual ,cast(0 as decimal(18,2)) Week_Plan,cast(0 as decimal(18,2)) Week_Actual,cast('' as nvarchar(600)) Remarks ");
            strSql.AppendLine(" INTO #LHCSystemListTemp from #AllLHCSystemListTemp group by isnull([Type],'0'); ");
            strSql.AppendLine("  update a set a.Cumulative_Plan=(select count(1) from #AllLHCSystemListTemp b where isnull(b.[Type],'0')=a.[Type] AND isnull(b.PlanFinishofTestingDate,'')<>'') ");
            strSql.AppendLine("  ,a.Cumulative_Actual=(select count(1) from #AllLHCSystemListTemp b where isnull(b.[Type],'0')=a.[Type] AND isnull(b.ActualFinishedDate,'')<>'') ");
            strSql.AppendLine("  ,a.Week_Plan=(select count(1) from #AllLHCSystemListTemp b where isnull(b.[Type],'0')=a.[Type] AND b.PlanFinishofTestingDate>=@StartWeebTime AND b.PlanFinishofTestingDate<=@EndWeebTime) ");
            strSql.AppendLine("  ,a.Week_Actual=(select count(1) from #AllLHCSystemListTemp b where isnull(b.[Type],'0')=a.[Type] AND b.ActualFinishedDate>=@StartWeebTime AND b.ActualFinishedDate<=@EndWeebTime) ");
            strSql.AppendLine("  ,a.Remarks=(select top 1 Remarks from Transfer_SystemStatusRemarks b(NOLOCK) where a.Category=b.TypeName and b.ProjectId=@ProjectId) ");
            strSql.AppendLine("  from #LHCSystemListTemp a; ");
            strSql.AppendLine("  select * from #LHCSystemListTemp; ");
            listStr.Add(new SqlParameter("@ProjectId", this.CurrUser.LoginProjectId));
            listStr.Add(new SqlParameter("@StartWeebTime", startWeebTime));
            listStr.Add(new SqlParameter("@EndWeebTime", dayOfWeek));
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(strSql.ToString(), parameter);
            Grid1.RecordCount = tb.Rows.Count;
            Grid1.DataSource = tb;
            Grid1.DataBind();
            //合计
            int Cumulative_Plan = 0;
            int Cumulative_Actual = 0;
            int Week_Plan = 0;
            int Week_Actual = 0;
            int System_Qty = 0;
            foreach (DataRow row in tb.Rows)
            {
                System_Qty += Convert.ToInt32(row["System_Qty"]);
                Cumulative_Plan += Convert.ToInt32(row["Cumulative_Plan"]);
                Cumulative_Actual += Convert.ToInt32(row["Cumulative_Actual"]);
                Week_Plan += Convert.ToInt32(row["Week_Plan"]);
                Week_Actual += Convert.ToInt32(row["Week_Actual"]);
            }
            JObject summary = new JObject();
            summary.Add("Category", "Total");
            summary.Add("System_Qty", System_Qty.ToString());
            summary.Add("Cumulative_Plan", Cumulative_Plan.ToString());
            summary.Add("Cumulative_Actual", Cumulative_Actual.ToString());
            summary.Add("Week_Plan", Week_Plan.ToString());
            summary.Add("Week_Actual", Week_Actual.ToString());
            Grid1.SummaryData = summary;
        }
        /// 
        /// 查询绑定图表数据
        /// 
        public void AnalyseData()
        {
            var forms = from x in Funs.DB.Transfer_LHCSystemList
                        where x.ProjectId == this.CurrUser.LoginProjectId
                        select x;
            string _dateType = ddlDateType.SelectedValue;
            #region 按照当前日期前一周数据
            if (_dateType == "1")
            {
                ///按单位统计
                DataTable dtTime = new DataTable();
                dtTime.Columns.Add("日期", typeof(string));
                dtTime.Columns.Add("计划完成数量", typeof(string));
                dtTime.Columns.Add("实际完成数量", typeof(string));
                dtTime.Columns.Add("进行中移交包数量", typeof(string));
                for (int i = 6; i >= 0; i--)
                {
                    DataRow rowTime = dtTime.NewRow();
                    DateTime QueryTime = DateTime.Now.AddDays(i * -1);
                    rowTime["日期"] = QueryTime.ToString("yyyy/MM/dd");
                    DateTime startTime = Convert.ToDateTime(QueryTime.ToString("yyyy-MM-dd") + " 00:00:00");
                    DateTime endTime = Convert.ToDateTime(QueryTime.ToString("yyyy-MM-dd") + " 23:59:59");
                    rowTime["计划完成数量"] = forms.Where(x => x.PlanFinishofTestingDate <= endTime).Count();
                    rowTime["实际完成数量"] = forms.Where(x => x.ActualFinishedDate <= endTime).Count();
                    rowTime["进行中移交包数量"] = forms.Where(x => x.UpdateTime <= endTime && x.Status == "In progress").Count();
                    dtTime.Rows.Add(rowTime);
                }
                this.ChartAccidentTime.CreateChart(BLL.ChartControlService.GetDataSourceChart(dtTime, "尾项完成统计分析", this.drpChartType.SelectedValue, 1300, 550, false));
            }
            #endregion
            //按照当前月份到一月份的数据
            if (_dateType == "2")
            {
                ///按单位统计
                DataTable dtTime = new DataTable();
                dtTime.Columns.Add("月份", typeof(string));
                dtTime.Columns.Add("计划完成数量", typeof(string));
                dtTime.Columns.Add("实际完成数量", typeof(string));
                dtTime.Columns.Add("进行中移交包数量", typeof(string));
                for (int i = 1; i <= DateTime.Now.Month; i++)
                {
                    DataRow rowTime = dtTime.NewRow();
                    DateTime QueryTime = Convert.ToDateTime($"{DateTime.Now.Year.ToString()}-{i}-1 00:00:00");
                    rowTime["月份"] = QueryTime.ToString("yyyy/MM");
                    DateTime startTime = QueryTime;
                    DateTime endTime = Convert.ToDateTime(QueryTime.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd") + " 23:59:59");
                    rowTime["计划完成数量"] = forms.Where(x => x.PlanFinishofTestingDate <= endTime).Count();
                    rowTime["实际完成数量"] = forms.Where(x => x.ActualFinishedDate <= endTime).Count();
                    rowTime["进行中移交包数量"] = forms.Where(x => x.UpdateTime <= endTime && x.Status == "In progress").Count();
                    dtTime.Rows.Add(rowTime);
                }
                this.ChartAccidentTime.CreateChart(BLL.ChartControlService.GetDataSourceChart(dtTime, "尾项完成统计分析", this.drpChartType.SelectedValue, 1300, 550, false));
            }
        }
        protected void TabStrip1_TabIndexChanged(object sender, EventArgs e)
        {
            if (TabStrip1.ActiveTabIndex == 0)
            {
                BindGrid1();
            }
            else if (TabStrip1.ActiveTabIndex == 1)
            {
                AnalyseData();
            }
        }
        /// 
        /// 图形变换 
        /// 
        /// 
        /// 
        protected void drpChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.AnalyseData();
        }
        /// 
        /// 现在日期类型
        /// 
        /// 
        /// 
        protected void ddlDateType_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.AnalyseData();
        }
        /// 
        /// 修改后事件
        /// 
        /// 
        /// 
        protected void Grid1_AfterEdit(object sender, GridAfterEditEventArgs e)
        {
            Dictionary> modifiedDict = Grid1.GetModifiedDict();
            foreach (int rowIndex in modifiedDict.Keys)
            {
                string rowID = Grid1.DataKeys[rowIndex][0].ToString();
                string remarks = modifiedDict[rowIndex]["Remarks"].ToString();
                var updateRemarks = Funs.DB.Transfer_SystemStatusRemarks.FirstOrDefault(p => p.TypeName == rowID && p.ProjectId == this.CurrUser.LoginProjectId);
                if (updateRemarks != null)
                {
                    updateRemarks.Remarks = remarks;
                    Funs.DB.SubmitChanges();
                }
                else
                {
                    Model.Transfer_SystemStatusRemarks AddRemarks = new Model.Transfer_SystemStatusRemarks();
                    AddRemarks.Id = Guid.NewGuid().ToString();
                    AddRemarks.ProjectId = this.CurrUser.LoginProjectId;
                    AddRemarks.TypeName= rowID;
                    AddRemarks.Remarks= remarks;
                    Funs.DB.Transfer_SystemStatusRemarks.InsertOnSubmit(AddRemarks);
                    Funs.DB.SubmitChanges();
                }
            }
        }
    }
}