using BLL;
using Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web.UI.WebControls;

namespace FineUIPro.Web.ManHours
{
    public partial class ManHoursPlanEditNew : PageBase
    {
        /// <summary>
        /// 加载表头
        /// </summary>
        protected void Page_Init(object sender, EventArgs e)
        {
            InitGrid();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetButtonPower();//权限设置
                this.btnClose.OnClientClick = ActiveWindow.GetHideReference();
                BindGrid();

                int years = DateTime.Now.Year;
                int month = DateTime.Now.Month;
                string curMonthManHour = string.Empty;
                var q1 = from x in Funs.DB.Sys_ActualManHourMonthSet where Convert.ToInt32(x.Years) == years && x.DepartId == null select x;
                var q2 = from x in Funs.DB.Sys_ActualManHourMonthSet where Convert.ToInt32(x.Years) == years + 1 && x.DepartId == null select x;
                if (q1.Count() > 0)
                {
                    curMonthManHour = q1.First().Month1 + "|" + q1.First().Month2 + "|"
                    + q1.First().Month3 + "|" + q1.First().Month4 + "|"
                    + q1.First().Month5 + "|" + q1.First().Month6 + "|" + q1.First().Month7 + "|"
                    + q1.First().Month8 + "|" + q1.First().Month9 + "|"
                    + q1.First().Month10 + "|" + q1.First().Month11 + "|" + q1.First().Month12 + "|";

                    #region
                    //if (month == 1)
                    //{
                    //    curMonthManHour = q.First().Month1.HasValue ? q.First().Month1.Value : 0;
                    //}
                    //if (month == 2)
                    //{
                    //    curMonthManHour = q.First().Month2.HasValue ? q.First().Month2.Value : 0;
                    //}
                    //if (month == 3)
                    //{
                    //    curMonthManHour = q.First().Month3.HasValue ? q.First().Month3.Value : 0;
                    //}
                    //if (month == 4)
                    //{
                    //    curMonthManHour = q.First().Month4.HasValue ? q.First().Month4.Value : 0;
                    //}
                    //if (month == 5)
                    //{
                    //    curMonthManHour = q.First().Month5.HasValue ? q.First().Month5.Value : 0;
                    //}
                    //if (month == 6)
                    //{
                    //    curMonthManHour = q.First().Month6.HasValue ? q.First().Month6.Value : 0;
                    //}
                    //if (month == 7)
                    //{
                    //    curMonthManHour = q.First().Month7.HasValue ? q.First().Month7.Value : 0;
                    //}
                    //if (month == 8)
                    //{
                    //    curMonthManHour = q.First().Month8.HasValue ? q.First().Month8.Value : 0;
                    //}
                    //if (month == 9)
                    //{
                    //    curMonthManHour = q.First().Month9.HasValue ? q.First().Month9.Value : 0;
                    //}
                    //if (month == 10)
                    //{
                    //    curMonthManHour = q.First().Month10.HasValue ? q.First().Month10.Value : 0;
                    //}
                    //if (month == 11)
                    //{
                    //    curMonthManHour = q.First().Month11.HasValue ? q.First().Month11.Value : 0;
                    //}
                    //if (month == 12)
                    //{
                    //    curMonthManHour = q.First().Month12.HasValue ? q.First().Month12.Value : 0;
                    //}
                    //hidCurMonthManHour.Text = curMonthManHour.ToString();
                    #endregion

                }
                if (q2.Count() > 0)
                {
                    curMonthManHour = curMonthManHour + q2.First().Month1 + "|" + q2.First().Month2 + "|"
                    + q2.First().Month3 + "|" + q2.First().Month4 + "|"
                    + q2.First().Month5 + "|" + q2.First().Month6 + "|" + q2.First().Month7 + "|"
                    + q2.First().Month8 + "|" + q2.First().Month9 + "|"
                    + q2.First().Month10 + "|" + q2.First().Month11 + "|" + q2.First().Month12 + "|";
                }
                hidCurMonthManHour.Text = curMonthManHour.Substring(0, curMonthManHour.Length - 1);
            }
        }

        #region 表头
        /// <summary>
        /// 表头
        /// </summary>
        private void InitGrid()
        {
            string m = "";
            int Month = 0;
            int Year = DateTime.Now.Year;

            int day = DateTime.Now.Day;
            //如果26号到31号则显示当月 
            if (day >= 26)
            {
                Month = DateTime.Now.Month - 1;
            }
            // 如果1-5号则显示上个月
            else
            {
                Month = DateTime.Now.Month - 2;
            }

            for (int i = 0; i < 12; i++)
            {
                RenderField rd = new RenderField();
                rd.Width = Unit.Pixel(70);
                Year = Month + 1 > 12 ? Year + 1 : Year;
                Month = Month + 1 > 12 ? 1 : Month + 1;
                m = Month < 10 ? "0" + Month : Month.ToString();
                rd.HeaderText = Year.ToString() + m;
                rd.FieldType = FieldType.Float;
                rd.ColumnID = Year.ToString() + "-" + m.ToString();
                if (i > 0)
                {
                    NumberBox num = new NumberBox();
                    num.NoNegative = true;
                    num.ID = Year.ToString() + "-" + m.ToString() + "-Editor";
                    rd.Editor.Add(num);
                }
                Grid1.Columns.Add(rd);
            }
        }
        #endregion

        #region 绑定数据
        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindGrid()
        {
            SqlParameter[] parameter = new SqlParameter[]
                    {
                        new SqlParameter("@engineerId",Request.Params["UserId"].ToString())
                    };
            DataSet ds = SQLHelper.RunProcedure("Proc_ManHoursPlanEditNew", parameter, "tt");
            DataTable table = ds.Tables[0];
            if (table.Rows.Count > 0)
            {
                Grid1.DataSource = table;
                Grid1.DataBind();
            }

            var manHourDetails = new List<ManHours_PlanDetail>();
            var actHours = new List<ManHours_Actual>();
            var manHoursPlanIds = table.AsEnumerable().Select(s => s.Field<string>("ManHoursPlanId")).ToList();
            manHoursPlanIds.Remove("");

            if (manHoursPlanIds.Count > 0)
            {
                manHourDetails = Funs.DB.ManHours_PlanDetail.Where(p => manHoursPlanIds.Contains(p.PlanManHoursId)).ToList();
                actHours = Funs.DB.ManHours_Actual.Where(p => manHoursPlanIds.Contains(p.ManHoursPlanId)).ToList();
            }

            for (int row = 0; row < Grid1.Rows.Count; row++)
            {
                string manHoursPlanId = Grid1.DataKeys[row][0].ToString();

                var manHourDetail = manHourDetails.Where(p => p.PlanManHoursId == manHoursPlanId);
                var actHour = actHours.Where(p => p.ManHoursPlanId == manHoursPlanId);

                string m = "";
                int Month = 0;
                int Year = DateTime.Now.Year;

                int day = DateTime.Now.Day;
                //如果26号到31号则显示当月 
                if (day >= 26)
                {
                    Month = DateTime.Now.Month - 1;
                }
                // 如果1-5号则显示上个月
                else
                {
                    Month = DateTime.Now.Month - 2;
                }

                double? total = Convert.ToDouble(Grid1.Rows[row].Values[17]); // 实际人工时;
                double? planMan = Convert.ToDouble(Grid1.Rows[row].Values[16]);  // 计划人工时

                for (int i = 0; i < 12; i++)
                {
                    RenderField rd;
                    Year = Month + 1 > 12 ? Year + 1 : Year;
                    Month = Month + 1 > 12 ? 1 : Month + 1;
                    m = Month < 10 ? "0" + Month : Month.ToString();
                    rd = Grid1.FindColumn(Year.ToString() + "-" + m.ToString()) as RenderField;
                    double h = 0;
                    if (i == 0)
                    {
                        if (actHour.Count() > 0)
                        {
                            var act = from x in actHour where x.ManHoursDate == Year.ToString() + m select x.Hours;
                            if (act.Count() > 0)
                            {
                                if (act.Count() == 1)
                                {
                                    Grid1.Rows[row].Values[rd.ColumnIndex] = act.First();
                                }
                                else
                                {
                                    double hour = 0;
                                    foreach (var q in act)
                                    {
                                        hour = hour + (q != null ? q.Value : 0);
                                    }
                                    Grid1.Rows[row].Values[rd.ColumnIndex] = hour;
                                }

                            }
                            else
                            {
                                Grid1.Rows[row].Values[rd.ColumnIndex] = 0;
                            }
                        }
                        else
                        {
                            Grid1.Rows[row].Values[rd.ColumnIndex] = 0;
                        }

                    }
                    else
                    {
                        var hours = from x in manHourDetail where x.DateMonth.Value.Year == Year && x.DateMonth.Value.Month == Month select x.Hour;
                        if (hours.Count() > 0)
                        {
                            Grid1.Rows[row].Values[rd.ColumnIndex] = hours.First();
                            h = hours.First() != null ? hours.First().Value : 0;
                        }
                        else
                        {
                            Grid1.Rows[row].Values[rd.ColumnIndex] = 0;
                        }
                    }
                    total += h;
                }
                if (total != null)
                {
                    Grid1.Rows[row].Values[18] = total;
                }
                else
                {
                    Grid1.Rows[row].Values[18] = 0;
                }
                if (planMan != null && planMan != 0 && total != null)
                {
                    RenderField r = Grid1.FindColumn("Realization") as RenderField;
                    double rate = (1.0 * total.Value / planMan.Value);
                    string real = rate.ToString("0.00");
                    Grid1.Rows[row].Values[r.ColumnIndex] = real;
                    if (rate > 1)
                    {
                        Grid1.Rows[row].CellCssClasses[r.ColumnIndex] = "totalRed";
                    }
                }
            }
        }

        /// <summary>
        /// 绑定默认值
        /// </summary>
        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            string manHoursPlanId = e.RowID;
            var manHourDetail = from x in Funs.DB.ManHours_PlanDetail where x.PlanManHoursId == manHoursPlanId select x;
            var actHour = from x in Funs.DB.ManHours_Actual where x.ManHoursPlanId == manHoursPlanId select x;
            string m = "";
            int Month = 0;
            int Year = DateTime.Now.Year;

            int day = DateTime.Now.Day;
            //如果26号到31号则显示当月 
            if (day >= 26)
            {
                Month = DateTime.Now.Month - 1;
            }
            // 如果1-5号则显示上个月
            else
            {
                Month = DateTime.Now.Month - 2;
            }

            double? total = Convert.ToDouble(e.Values[17]); // 实际人工时;
            double? planMan = Convert.ToDouble(e.Values[16]);  // 计划人工时

            for (int i = 0; i < 12; i++)
            {
                RenderField rd;
                Year = Month + 1 > 12 ? Year + 1 : Year;
                Month = Month + 1 > 12 ? 1 : Month + 1;
                m = Month < 10 ? "0" + Month : Month.ToString();
                rd = Grid1.FindColumn(Year.ToString() + "-" + m.ToString()) as RenderField;
                double h = 0;
                if (i == 0)
                {
                    if (actHour.Count() > 0)
                    {
                        var act = from x in actHour where x.ManHoursDate == Year.ToString() + m select x.Hours;
                        if (act.Count() > 0)
                        {
                            if (act.Count() == 1)
                            {
                                e.Values[rd.ColumnIndex] = act.First();
                            }
                            else
                            {
                                double hour = 0;
                                foreach (var q in act)
                                {
                                    hour = hour + (q != null ? q.Value : 0);
                                }
                                e.Values[rd.ColumnIndex] = hour;
                            }

                        }
                        else
                        {
                            e.Values[rd.ColumnIndex] = 0;
                        }
                    }
                    else
                    {
                        e.Values[rd.ColumnIndex] = 0;
                    }

                }
                else
                {
                    var hours = from x in manHourDetail where x.DateMonth.Value.Year == Year && x.DateMonth.Value.Month == Month select x.Hour;
                    if (hours.Count() > 0)
                    {
                        e.Values[rd.ColumnIndex] = hours.First();
                        h = hours.First() != null ? hours.First().Value : 0;
                    }
                    else
                    {
                        e.Values[rd.ColumnIndex] = 0;
                    }
                }
                total += h;
            }
            if (total != null)
            {
                e.Values[18] = total;
            }
            else
            {
                e.Values[18] = 0;
            }
            if (planMan != null && planMan != 0 && total != null)
            {
                RenderField r = Grid1.FindColumn("Realization") as RenderField;
                double rate = (1.0 * total.Value / planMan.Value);
                string real = rate.ToString("0.00");
                e.Values[r.ColumnIndex] = real;
                if (rate > 1)
                {
                    e.CellCssClasses[r.ColumnIndex] = "totalRed";
                }
            }

        }
        #endregion

        #region 保存
        /// <summary>
        /// 保存
        /// </summary>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if ((DateTime.Now.Day > 10 || (DateTime.Now.Day == 10 && DateTime.Now.Hour > 17)) && DateTime.Now.Day < 26)
            {
                Alert.ShowInParent("StaffingPlan已冻结!提示:下月计划人工时从本月26号开放填写,到下月10号下午5点冻结!");
                return;
            }
            JArray mergedData = Grid1.GetMergedData();

            Model.EProjectDB db = Funs.DB;

            List<Model.ManHours_PlanDetail> deletePlanDetail = new List<Model.ManHours_PlanDetail>();
            List<Model.ManHours_PlanDetail> addPlanDetail = new List<Model.ManHours_PlanDetail>();

            foreach (JObject mergedRow in mergedData)
            {
                int Month = 0;
                int Year = DateTime.Now.Year;
                int day = DateTime.Now.Day;
                //如果26号到31号则显示当月 
                if (day >= 26)
                {
                    Month = DateTime.Now.Month - 1;
                }
                // 如果1-10号则显示上个月
                else
                {
                    Month = DateTime.Now.Month - 2;
                }

                JObject values = mergedRow.Value<JObject>("values");
                string rowId = values.Value<string>("ManHoursPlanId");
                var manPlanHour = BLL.PlanService.GetPlanByIds(rowId);
                var manHourDetail = from x in db.ManHours_PlanDetail where x.PlanManHoursId == rowId select x;

                for (int i = 0; i < 12; i++)
                {
                    Year = Month + 1 > 12 ? Year + 1 : Year;
                    Month = Month + 1 > 12 ? 1 : Month + 1;
                    string month = Month < 10 ? "0" + Month : Month.ToString();
                    if (i > 0)
                    {
                        Model.ManHours_PlanDetail detail = new Model.ManHours_PlanDetail();
                        detail.ManHoursPlanDetailId = Guid.NewGuid().ToString();
                        detail.PlanManHoursId = rowId;
                        detail.EProjectId = manPlanHour.EProjectId;
                        detail.UserId = manPlanHour.EngineerId;
                        detail.UserName = manPlanHour.EngineerName;
                        var hours = from x in manHourDetail where x.DateMonth.Value.Year == Year && x.DateMonth.Value.Month == Month select x;

                        if (hours.Count() > 0)
                        {
                            deletePlanDetail.Add(hours.First());
                            //db.ManHours_PlanDetail.DeleteAllOnSubmit(hours);
                        }

                        if (day > 28)
                        {
                            day = 28;
                        }

                        detail.DateMonth = Convert.ToDateTime(Year.ToString() + "-" + Month.ToString() + "-" + day.ToString());
                        string date = Year.ToString() + "-" + month.ToString();
                        string manh = values.Value<string>(date);

                        if (!string.IsNullOrEmpty(manh))
                        {
                            detail.Hour = Convert.ToDouble(manh);
                        }
                        else
                        {
                            detail.Hour = 0;
                        }
                        addPlanDetail.Add(detail);
                    }
                }
            }
            db.ManHours_PlanDetail.DeleteAllOnSubmit(deletePlanDetail);
            db.ManHours_PlanDetail.InsertAllOnSubmit(addPlanDetail);
            db.SubmitChanges();
            //BindGrid();
            ShowNotify("数据保存成功!(表格数据已重新绑定)");
        }

        //private void UpdateDataRow(Dictionary<string, object> rowDict, DataRow rowData)
        //{
        //    string m = "";
        //    int Year = DateTime.Now.Year;
        //    int Month = DateTime.Now.Month - 1;
        //    for (int i = 0; i < 12; i++)
        //    {
        //        Year = Month + 1 > 12 ? Year + 1 : Year;
        //        Month = Month + 1 > 12 ? 1 : Month + 1;
        //        m = Month < 10 ? "0" + Month : Month.ToString();
        //        UpdateDataRow(Year.ToString() + "-" + m.ToString(), rowDict, rowData);
        //    }
        //}
        //private void UpdateDataRow(string columnName, Dictionary<string, object> rowDict, DataRow rowData)
        //{
        //    if (rowDict.ContainsKey(columnName))
        //    {
        //        rowData[columnName] = rowDict[columnName];
        //    }
        //}
        /// <summary>
        /// 根据行ID来获取行数据
        /// </summary>
        //private DataRow FindRowByID(string rowID)
        //{
        //    SqlParameter[] parameter = new SqlParameter[]
        //            {
        //                new SqlParameter("@sId",Request.Params["UserId"].ToString())
        //            };
        //    DataSet ds = SQLHelper.RunProcedure("Proc_ManHoursPlanEdit", parameter, "tt");
        //    DataTable table = ds.Tables[0];
        //    foreach (DataRow row in table.Rows)
        //    {
        //        if (row["EProjectId"].ToString() == rowID)
        //        {
        //            return row;
        //        }
        //    }
        //    return null;
        //}
        #endregion

        #region 权限设置
        /// <summary>
        /// 菜单按钮权限
        /// </summary>
        private void GetButtonPower()
        {
            var buttonList = BLL.CommonService.GetAllButtonList(this.CurrUser.UserId, BLL.Const.ManHoursMenuId);
            if (buttonList.Count() > 0)
            {
                if (buttonList.Contains(BLL.Const.BtnStaffingPlan))
                {
                    this.btnSave.Hidden = false;
                }
            }
        }
        #endregion
    }
}