using BLL;
using Model;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace FineUIPro.Web.common
{
    public partial class mainMenu_PDigData : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //getEmployInOutRecords = Funs.DB.T_d_EmployInOutRecord.Where(x => x.ProjectId == this.CurrUser.LoginProjectId && x.RecordDate.Value == DateTime.Now.Date).ToList();
                //getPersons = Funs.DB.SitePerson_Person.Where(x => x.ProjectId == this.CurrUser.LoginProjectId && x.IsUsed == true 
                //    && x.InTime <= DateTime.Now && (!x.OutTime.HasValue || x.OutTime > DateTime.Now)).ToList(); 
                
                ///当前现场总人数
                getSitePerson();             
            }
        }

        #region 当前现场总人数
        /// <summary>
        ///  当前现场总人数
        /// </summary>
        private void getSitePerson()
        {
            //var AllCount = ( from x in Funs.DB.T_d_EmployInOutRecord.Where(x => x.ProjectId == this.CurrUser.LoginProjectId && x.RecordDate.Value == DateTime.Now.Date)
            //                from y in Funs.DB.SitePerson_Person.Where(y=>y.ProjectId== this.CurrUser.LoginProjectId && y.IsUsed==true)
            //                select x.IDCardNo).Distinct().Count();
            var AllCount = (from x in Funs.DB.T_d_EmployInOutRecord
                            join y in Funs.DB.SitePerson_Person on new { ss1 = x.ProjectId, ss = x.IDCardNo } equals new { ss1 = y.ProjectId, ss = y.IdentityCard }
                            where y.ProjectId == this.CurrUser.LoginProjectId && y.IsUsed == true && x.ProjectId== this.CurrUser.LoginProjectId && x.RecordDate.Value == DateTime.Now.Date
                            select x.IDCardNo).Distinct().Count();
            if (AllCount > 0)
            {
                ////总人数
                this.divperson.InnerHtml = ((AllCount % 10000) / 1000).ToString();
                this.person00.InnerHtml = ((AllCount % 1000) / 100).ToString();
                this.person01.InnerHtml = ((AllCount % 100) / 10).ToString();
                this.person02.InnerHtml = (AllCount % 10).ToString();
            }
        }
        #endregion

        #region 项目安全人工时
        /// <summary>
        ///  项目安全人工时
        /// </summary>
        protected string Two
        {
            get
            {
                List<Model.SingleSerie> series = new List<Model.SingleSerie>();
                Model.BusinessColumn businessColumn = new Model.BusinessColumn();
                List<string> listCategories = new List<string>();
                businessColumn.title = "项目安全人工时";
                Model.SingleSerie s = new Model.SingleSerie();
                List<double> listdata = new List<double>();

                Model.SingleSerie s2 = new Model.SingleSerie();
                List<double> listdata2 = new List<double>();
                var getMonts = SitePerson_MonthReportService.getMonthReports(CurrUser.LoginProjectId, null);
                foreach (var month in getMonts.OrderBy(x => x.CompileDate))
                {
                    listCategories.Add(string.Format("{0:yyyy-MM}", month.CompileDate));
                    listdata.Add(double.Parse((month.TotalPersonWorkTime ?? 0).ToString()));
                    listdata2.Add(double.Parse((month.DayWorkTime ?? 0).ToString()));
                }
                s.data = listdata;
                series.Add(s);
                s2.data = listdata2;
                series.Add(s2);
                businessColumn.categories = listCategories;
                businessColumn.series = series;
                return JsonConvert.SerializeObject(businessColumn);
            }
        }
        #endregion
                
        #region  现场人员
        /// <summary>
        /// 
        /// </summary>
        public static List<Model.T_d_EmployInOutRecord> getEmployInOutRecords;
        /// <summary>
        /// 
        /// </summary>
        public static List<Model.SitePerson_Person> getPersons;

        /// <summary>
        /// 按单位统计
        /// </summary>
        protected string Four1
        {
            get
            {
                //string sql = @"
                //select b.*,a.numa,c.UnitName from(
                //select UnitId, COUNT(distinct IDCardNo) numa from  T_d_EmployInOutRecord
                //    where ProjectId = '" + CurrUser.LoginProjectId + "' and RecordDate = '"+DateTime.Now.ToString("yyyy-MM-dd")+ @"'
                //    group by UnitId)a right join
                //    (
                //    select UnitId, COUNT(1) numb from SitePerson_Person
                //    where ProjectId = '" + CurrUser.LoginProjectId + "' and IsUsed = 1 and InTime < '"+DateTime.Now.ToString("yyyy-MM-dd")+"' and(OutTime is null or OutTime > '"+ DateTime.Now.ToString("yyyy-MM-dd") +@"')
                //    group by UnitId
                //    )b on a.UnitId = b.UnitId left join Base_unit c on b.unitId=c.UnitId
                //    ";
                string sql = @"SELECT  
	                            p.UnitId
	                            ,ISNULL((case when u.UnitName=''then null else u.UnitName end),'未知') AS UnitName
	                            ,COUNT( distinct  IDCardNo) AS numa 
	                            ,COUNT( distinct PersonId)   AS numb
                            FROM dbo.SitePerson_Person AS P
                            LEFT  JOIN ( select ProjectId,IDCardNo,SUM(ISNULL(ManHours,0)) ManHours from t_d_EmployInOutRecord where     RecordDate >='" + DateTime.Now.ToString("yyyy-MM-dd")+ @"' 
                            AND  RecordDate <= '" + DateTime.Now.ToString("yyyy-MM-dd") + @"' 
                            group by ProjectId,IDCardNo)  T  ON P.ProjectId=T.ProjectId AND T.IDCardNo=P.IdentityCard
                            LEFT JOIN dbo.Base_Unit AS U ON P.UnitId=U.UnitId
                            LEFT JOIN dbo.Project_ProjectUnit AS pu ON pu.UnitId=p.UnitId and pu.ProjectId=p.ProjectId
                            WHERE   pu.ProjectId is not null and P.ProjectId ='" + CurrUser.LoginProjectId + @"'	  and P.InTime <=GETDATE() and ( P.OutTime is null or P.OutTime > GETDATE())  and p.IsUsed =1 
 
                            GROUP BY P.UnitId,U.UnitName

                    ";
                DataTable tb41 = SQLHelper.GetDataTableRunText(sql);

                List<Model.SingleSerie> series = new List<Model.SingleSerie>();
                Model.BusinessColumn businessColumn = new Model.BusinessColumn();
                List<string> listCategories = new List<string>();
                Model.SingleSerie s = new Model.SingleSerie();
                Model.SingleSerie s2 = new Model.SingleSerie();
                List<double> listdata = new List<double>();
                List<double> listdata2 = new List<double>();
                businessColumn.title = "现场人员";
                
                if (tb41.Rows.Count > 0)
                {
                    foreach (DataRow row in tb41.Rows)
                    {
                        listCategories.Add(UnitService.GetShortUnitNameByUnitId(row["UnitId"].ToString()) ?? "未知");
                        if (!string.IsNullOrEmpty(row["numa"].ToString()))
                        {
                            listdata.Add(double.Parse(row["numa"].ToString()));
                        }
                        else
                        {
                            listdata.Add(0);

                        }

                        listdata2.Add(double.Parse(row["numb"].ToString()));
                    }
                }
                //else
                //{
                //    var getunits = UnitService.GetUnitByProjectIdList(this.CurrUser.LoginProjectId).Take(10);
                //    foreach (var unit in getunits)
                //    {
                //        string name = unit.ShortUnitName ?? unit.UnitName;
                //        if (string.IsNullOrEmpty(unit.UnitId) || string.IsNullOrEmpty(name))
                //        {
                //            name = "未知";
                //        }
                //        listCategories.Add(unit.ShortUnitName ?? unit.UnitName);
                        
                //        listdata.Add(0);
                //        listdata2.Add(0);
                //    }
                //}
                s.data = listdata;
                series.Add(s);

                s2.data = listdata2;
                series.Add(s2);

                businessColumn.categories = listCategories;
                businessColumn.series = series;
                return JsonConvert.SerializeObject(businessColumn);
            }
        }

        /// <summary>
        /// 按岗位统计
        /// </summary>
        protected string Four2
        {
            get
            {
                string sql = @"
                select b.*,a.numa,c.WorkPostName from(
                select a.PostId, a.PostName, COUNT(1) numa from  T_d_EmployInOutRecord a left join  SitePerson_Person b on  a.IDCardNo = b.IdentityCard and a.ProjectId =b.ProjectId
                    where a.ProjectId = '" + CurrUser.LoginProjectId + "' and RecordDate = '" + DateTime.Now.ToString("yyyy-MM-dd") + @"' and IsUsed = 1 and InTime < '" + DateTime.Now.ToString("yyyy-MM-dd") + "' and(OutTime is null or OutTime > '" + DateTime.Now.ToString("yyyy-MM-dd") + @"')  
                    group by PostId,PostName)a right join
                    (
                    select WorkPostId, COUNT(1) numb from SitePerson_Person
                    where ProjectId = '" + CurrUser.LoginProjectId + "' and IsUsed = 1 and InTime < '" + DateTime.Now.ToString("yyyy-MM-dd") + "' and(OutTime is null or OutTime > '" + DateTime.Now.ToString("yyyy-MM-dd") + @"')
                    group by WorkPostId
                    )b on a.PostId = b.WorkPostId left join Base_WorkPost c on b.WorkPostId=c.WorkPostId
                    ";

                DataTable tb41 = SQLHelper.GetDataTableRunText(sql);
                List<Model.SingleSerie> series = new List<Model.SingleSerie>();
                Model.BusinessColumn businessColumn = new Model.BusinessColumn();
                List<string> listCategories = new List<string>();
                Model.SingleSerie s = new Model.SingleSerie();
                List<double> listdata = new List<double>();
                Model.SingleSerie s2 = new Model.SingleSerie();
                List<double> listdata2 = new List<double>();
                businessColumn.title = "现场人员";
               
                if (tb41.Rows.Count > 0)
                {
                    foreach (DataRow item in tb41.Rows)
                    {
                        listCategories.Add(item["WorkPostName"].ToString());
                        if (!string.IsNullOrEmpty(item["numa"].ToString()))
                        {
                            listdata.Add(double.Parse(item["numa"].ToString()));
                        }
                        else
                        {
                            listdata.Add(0);
                        }
                        listdata2.Add(double.Parse(item["numb"].ToString()));
                    }
                }
               // else
                //{
                //    var getpTypes = getPersons.Select(x => x.WorkPostId).Distinct();
                //    foreach (var item in getpTypes)
                //    {
                //        listCategories.Add(WorkPostService.getWorkPostNameById(item));
                         
                //        listdata.Add(0);
                //        listdata2.Add(0);
                //    }
                //}

                s.data = listdata;
                series.Add(s);
                s2.data = listdata2;
                series.Add(s2);
                businessColumn.categories = listCategories;
                businessColumn.series = series;
                return JsonConvert.SerializeObject(businessColumn);
            }
        }
        #endregion
                
    }
}