using BLL;
using BLL.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace FineUIPro.Web.ManHours
{
    public partial class ManHoursStatisticsNew : PageBase
    {
        #region 加载页面
        /// <summary>
        /// 加载页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string strSql1 = @" SELECT * FROM Sys_ActualManHourMonthSet where Years in ('" + (DateTime.Now.Year - 1) + "','" + (DateTime.Now.Year - 2) + "','" + DateTime.Now.Year + "','" + (DateTime.Now.Year + 1) + "')  and DepartId='" + BLL.Const.CTE_DepartId + "' order by Years";
                DataTable dt1 = SQLHelper.GetDataTableRunText(strSql1, null);
                if (dt1 != null && dt1.Rows.Count > 0)
                {
                    hidchildJson.Value = JsonHelper.DataTableToJSON(dt1);
                }
                string strSql = @" SELECT * FROM Sys_ActualManHourMonthSet where Years in ('" + (DateTime.Now.Year - 1) + "','" + (DateTime.Now.Year - 2) + "','" + DateTime.Now.Year + "','" + (DateTime.Now.Year + 1) + "') and DepartId is null order by Years";
                DataTable dt = SQLHelper.GetDataTableRunText(strSql, null);
                if (dt != null && dt.Rows.Count > 0)
                {
                    ActualManHour.Value = JsonHelper.DataTableToJSON(dt);
                }
                this.InitTreeMenu();//加载树
                BindGrid1(BLL.Const.CTE_DepartId);
                BindGrid2(BLL.Const.CTE_DepartId);
                WorkLoadData(BLL.Const.CTE_DepartId);
            }
        }
        #endregion

        #region 加载树
        /// <summary>
        /// 加载树
        /// </summary>
        private void InitTreeMenu()
        {
            this.tvControlItem.Nodes.Clear();
            TreeNode rootNode = new TreeNode();
            rootNode.Text = "CTE";
            rootNode.ToolTip = "CTE";
            rootNode.NodeID = "D1@" + BLL.Const.CTE_DepartId;
            //rootNode.Expanded = true;
            rootNode.EnableClickEvent = true;
            this.tvControlItem.Nodes.Add(rootNode);

            List<Model.Base_Depart> departs = BLL.DepartService.GetDepartListBySupCheckItem(BLL.Const.CTE_DepartId);

            foreach (var item in departs)
            {
                TreeNode departNode = new TreeNode();//定义根节点
                departNode.Text = item.DepartName;
                departNode.NodeID = "D2@"+ item.DepartId;
                departNode.ToolTip = item.DepartName;
                departNode.EnableClickEvent = true;
                //departNode.Expanded = true;
                rootNode.Nodes.Add(departNode);
                BindNodes(departNode, item.DepartId);
            }
        }

        /// <summary>
        /// 绑定树节点
        /// </summary>
        /// <param name="rootNode"></param>
        /// <param name="departId"></param>
        private void BindNodes(TreeNode rootNode, string departId)
        {
            List<Model.Sys_User> users = BLL.Sys_UserService.GetUserListByDepartId(departId);
            foreach (var item in users)
            {
                if (item.UserName.Contains(this.txtUserName.Text.Trim()))
                {
                    TreeNode userNode = new TreeNode();
                    userNode.Text = item.UserName;
                    userNode.NodeID = "UD@" + item.UserId + "@" + item.DepartId;
                    userNode.ToolTip = item.UserName;
                    userNode.EnableClickEvent = true;
                    //userNode.Expanded = true;
                    rootNode.Nodes.Add(userNode);
                }
            }
        }

        /// <summary>
        /// 姓名查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtUserName_TextChanged(object sender, EventArgs e)
        {
            InitTreeMenu();
        }
        #endregion

        #region 点击树节点
        /// <summary>
        /// 点击树节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void tvControlItem_NodeCommand(object sender, TreeCommandEventArgs e)
        {
            string[] ids = this.tvControlItem.SelectedNode.NodeID.Split('@');
            //hdId.Text = ids[ids.Length - 1];
            hdId.Text = ids[1];
            BindGrid1(hdId.Text);
            BindGrid2(hdId.Text);
            WorkLoadData(hdId.Text);
        }
        #endregion

        #region 绑定Grid
        /// <summary>
        /// Grid1绑定
        /// </summary>
        private void BindGrid1(string id)
        {
            var depart = BLL.DepartService.GetDepartById(id);
            List<SqlParameter> listStr = new List<SqlParameter>();
            if (depart != null && depart.DepartName != "CTE")
            {
                listStr.Add(new SqlParameter("@departId", depart.DepartId));
            }
            var user = BLL.Sys_UserService.GetCTEUserByUserId(id);
            if (user != null)
            {
                listStr.Add(new SqlParameter("@userId", user.UserId));
            }
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunProc("Proc_ManHoursStatisticsGrid1", parameter);
            Grid1.RecordCount = tb.Rows.Count;
            var table = this.GetPagedDataTable(Grid1, tb);
            Grid1.DataSource = table;
            Grid1.DataBind();
            OutputSummaryData1(tb);//计算和
        }
        private void OutputSummaryData1(DataTable tb)
        {
            float ManhoursPlan = 0.00f;
            //int ManhoursPlaned = 0.00f;
            float ManhoursActual = 0.00f;
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                ManhoursPlan += Convert.ToInt32(tb.Rows[i]["ManhoursPlan"]);
                //ManhoursPlaned += Convert.ToInt32(tb.Rows[i]["ManhoursPlaned"]);
                ManhoursActual += Convert.ToInt32(tb.Rows[i]["ManhoursActual"]);
            }
            JObject summary = new JObject();
            //summary.Add("major", "全部合计");
            summary.Add("ManhoursPlan", ManhoursPlan.ToString("F2"));
            //summary.Add("ManhoursPlaned", ManhoursPlaned.ToString("F2"));
            summary.Add("ManhoursActual", ManhoursActual.ToString("F2"));

            Grid1.SummaryData = summary;
        }

        /// <summary>
        /// Grid1分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            if (!string.IsNullOrEmpty(hdId.Text))
            {
                BindGrid1(hdId.Text);
            }
            else
            {
                BindGrid1("");
            }
        }

        /// <summary>
        /// Grid2绑定
        /// </summary>
        private void BindGrid2(string id)
        {
            var depart = BLL.DepartService.GetDepartById(hdId.Text.Trim());
            List<SqlParameter> listStr = new List<SqlParameter>();
            if (depart != null && depart.DepartName != "CTE")
            {
                listStr.Add(new SqlParameter("@departId", depart.DepartId));
            }
            var user = BLL.Sys_UserService.GetCTEUserByUserId(hdId.Text.Trim());
            if (user != null)
            {
                listStr.Add(new SqlParameter("@userId", user.UserId));
            }
            var eproject = BLL.EProjectService.GeteProjectById(id);
            if (eproject != null)
            {
                listStr.Add(new SqlParameter("@eprojectId", eproject.EProjectId));
            }
            //listStr.Add(new SqlParameter("@startDate", DateTime.Now.AddYears(-2).AddMonths(-1)));
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunProc("Proc_ManHoursStatisticsGrid2", parameter);
           
            //string json = JsonHelper1.DataTableToJSON(tb);
            //hidjson.Value = json;
            Grid2.DataSource = tb;
            Grid2.DataBind();
            OutputSummaryData2(tb);//计算和
        }

        /// <summary>
        /// Grid2合计列
        /// </summary>
        /// <param name="table"></param>
        private void OutputSummaryData2(DataTable tb)
        {
            float PlanHours = 0.00f;
            float ActualHours = 0.00f;
            float NoPlanHours = 0.00f;
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                PlanHours += Convert.ToInt32(tb.Rows[i]["PlanHours"]);
                ActualHours += Convert.ToInt32(tb.Rows[i]["ActualHours"]);
                NoPlanHours += Convert.ToInt32(tb.Rows[i]["NoPlanHours"]);
            }
            JObject summary = new JObject();
            //summary.Add("major", "全部合计");
            summary.Add("PlanHours", PlanHours.ToString("F2"));
            summary.Add("ActualHours", ActualHours.ToString("F2"));
            summary.Add("NoPlanHours", NoPlanHours.ToString("F2"));

            Grid2.SummaryData = summary;
        }

        /// <summary>
        /// 加载WorkLoad
        /// </summary>
        /// <param name="id"></param>
        private void WorkLoadData(string id)
        {
            var depart = BLL.DepartService.GetDepartById(hdId.Text.Trim());
            List<SqlParameter> listStr = new List<SqlParameter>();
            if (depart != null && depart.DepartName != "CTE")
            {
                listStr.Add(new SqlParameter("@departId", depart.DepartId));
            }
            var user = BLL.Sys_UserService.GetCTEUserByUserId(hdId.Text.Trim());
            if (user != null)
            {
                listStr.Add(new SqlParameter("@userId", user.UserId));
            }
            //var eproject = BLL.EProjectService.GeteProjectById(id);
            //if (eproject != null)
            //{
            //    listStr.Add(new SqlParameter("@eprojectId", eproject.EProjectId));
            //}
            listStr.Add(new SqlParameter("@startDate", DateTime.Now.AddYears(-2).AddMonths(-1)));
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunProc("Proc_ManHoursStatisticsGrid2", parameter);
            string json = JsonConvert.SerializeObject(tb);//JsonHelper1.DataTableToJSON(tb);
            hidjson.Value = json;
        }
        #endregion

        #region Grid1行点击事件
        /// <summary>
        /// Grid1行点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Grid1_RowSelect(object sender, GridRowSelectEventArgs e)
        {
            BindGrid2(this.Grid1.SelectedRowID);
        }
        #endregion
    }
}