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

namespace FineUIPro.Web.common
{
    public partial class mainProject : PageBase
    {
        #region 项目ID
        /// <summary>
        /// 项目ID
        /// </summary>
        public string ProjectId
        {
            get
            {
                return (string)ViewState["ProjectId"];
            }
            set
            {
                ViewState["ProjectId"] = value;
            }
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {           
            if (!IsPostBack)
            {
                this.ProjectId = string.Empty;
                if (this.CurrUser != null)
                {
                    this.ProjectId = this.CurrUser.LoginProjectId;
                }
                /// 获取安全人工时
                getPersonWorkTime();
                ///劳务统计
                getSitePerson();
                ///项目概况
                getProjectInfo();
                /// 获取质量问题
                getCQMSProblem();

                this.divQualityWarningNum.InnerHtml = (from x in Funs.DB.QualityAudit_PersonQuality
                                                  join y in Funs.DB.SitePerson_Person on x.PersonId equals y.PersonId
                                                  where y.ProjectId == this.ProjectId && x.LimitDate < DateTime.Now
                                                  select x).Count().ToString();
                ///产值
                getOutputValues();
                ///获取天气
                getWeatherValues();
            }
        }

        #region 安全人工时
        /// <summary>
        /// 获取安全人工时
        /// </summary>
        private void getPersonWorkTime()
        {
            this.divSafeWorkTime.InnerHtml = "0000000000";
           var ProjectTotal = (from x in Funs.DB.HSSE_MonthReportItem
             join y in Funs.DB.HSSE_MonthReport on x.MonthReportId equals y.MonthReportId
             where y.ProjectId == this.ProjectId  && "安全生产人工时数" == x.ReportItem
                               select x.YearTotal).Sum();

            if (ProjectTotal.HasValue)
            {
                this.divSafeWorkTime.InnerHtml = ProjectTotal.Value.ToString("0000000000"); ;
            }
            else
            {
                this.divSafeWorkTime.InnerHtml = "0000000000";
            }

            ///整改单          
            var getRectify = from x in Funs.DB.View_Hazard_HazardRegister
                             where x.ProjectId == this.ProjectId && x.States != Const.State_0 && x.States != null
                             group x by x.States into g
                             select new { g.Key,Count = g.Count()};
            var allcout = getRectify.ToList();
            if (allcout.Count > 0)
            {
                int total = 0;
                int finish = 0;
                foreach(var item in allcout)
                {
                    total += item.Count;
                    if (item.Key.ToString() == "3")
                    {
                        finish += item.Count;
                    }
                }

                this.divAllRectify.InnerHtml = total.ToString(); 
                this.divUCRectify .InnerHtml = (total - finish).ToString();
                this.divCRectify.InnerHtml = finish.ToString();
            }
        }
        #endregion

        #region 劳务统计
        protected string WorkPostS;
        protected string InPostCounts;
        protected string InDutyCounts;
        /// <summary>
        ///  劳务统计
        /// </summary>
        private void getSitePerson()
        {

            string sql = @"select c.ConstText,b.PostType,count( *) num from SitePerson_Person a left join Base_WorkPost b on a.WorkPostId=b.WorkPostId 
                         LEFT JOIN Sys_Const AS c ON c.ConstValue = b.PostType and   c.GroupId = 'PostType' and IsUsed =1 and InTime<='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and (OutTime is null or OutTime>'" + DateTime.Now.ToString("yyyy-MM-dd") + @"' )
                        where ProjectId='" + this.ProjectId + @"'
                        group by c.ConstText,b.PostType  ";
            List<SqlParameter> listStr = new List<SqlParameter>();
            SqlParameter[] parameter = listStr.ToArray();
            DataTable tb = SQLHelper.GetDataTableRunText(sql, parameter);
            int allcount = 0;
            int mcount = 0;
            if (tb != null)
            {
                foreach (DataRow row in tb.Rows)
                {
                    allcount += int.Parse(row["num"].ToString());
                    if (!string.IsNullOrEmpty(row["ConstText"].ToString()) && row["ConstText"].ToString().Contains("管理"))
                    {
                        mcount += int.Parse(row["num"].ToString());
                    }
                }
            }
            this.divALLPerson.InnerHtml = allcount.ToString();
            this.divGLPerson.InnerHtml = mcount.ToString();
            this.divZYPerson.InnerHtml = (allcount - mcount).ToString();          

            
            var getallin = APIPageDataService.getPersonInOutNum(this.ProjectId, DateTime.Now.AddDays(-1));            

            WorkPostS = "[]";
            InPostCounts = "[]";
            InDutyCounts = "[]";
            List<int> InPostCountList = new List<int>();
            List<int> InDutyCountList = new List<int>();
            List<string> worksList = new List<string>();
            var getPersons = Funs.DB.SitePerson_Person.Where(x => x.ProjectId == this.ProjectId && x.IsUsed == 1 && x.InTime <= DateTime.Now
            && !x.OutTime.HasValue);
            if (getPersons.Count() > 0)
            {
                var getWorkIds = getPersons.Where(x => x.WorkPostId != null).Select(x => x.WorkPostId).Distinct();
                if (getWorkIds.Count() > 0)
                {
                    foreach (var item in getWorkIds)
                    {
                        worksList.Add(WorkPostService.getWorkPostNameById(item));
                        int isPost = getPersons.Where(x => x.WorkPostId == item).Count();
                        InPostCountList.Add(isPost);
                        int inDuty = 0;
                        if (getallin.Count() > 0)
                        {
                            inDuty = getallin.Where(x => x.WorkPostId == item).Count();
                        }
                        InDutyCountList.Add(inDuty);
                    }
                }
            }
            else
            {
                worksList.Add(" ");
                InPostCountList.Add(0);
                InDutyCountList.Add(0);
            }

            WorkPostS = JsonConvert.SerializeObject(worksList);
            InPostCounts = JsonConvert.SerializeObject(InPostCountList);
            InDutyCounts = JsonConvert.SerializeObject(InDutyCountList);
        }
        #endregion

        #region 项目概况
        protected string divProjectNameTitle;
        protected string divProjectAddressTitle;
        protected string divProjectMoneyTitle;
        protected string divOwnUnitTitle;
        protected string divSGUnitTitle;
        protected string divJLUnitTitle;
        protected string divProjectImg;

        /// <summary>
        /// 
        /// </summary>
        private void getProjectInfo()
        {
            divProjectNameTitle = "";
            divProjectAddressTitle = "";
            divProjectMoneyTitle = "";
            divOwnUnitTitle = "";
            divSGUnitTitle = "";
            divJLUnitTitle = "";
            divProjectImg = "../res/indexv1/image/index2/center-bg.png";
            var project = ProjectService.GetProjectByProjectId(this.ProjectId);
            if (project != null)
            {               
                this.divProjectName.InnerHtml = project.ShortName;
                divProjectNameTitle = project.ProjectName;
                if (!string.IsNullOrEmpty(project.ProjectAddress))
                {
                    this.divProjectAddress.InnerHtml = project.ProjectAddress.Length >8 ? project.ProjectAddress.Substring(0,8) + "..." : project.ProjectAddress;
                    divProjectAddressTitle = project.ProjectAddress;
                }
                string unit_yz= ProjectService.getProjectUnitNameByUnitType(project.ProjectId, Const.ProjectUnitType_4);
                if (!string.IsNullOrEmpty(unit_yz))
                {
                    this.divOwnUnit.InnerHtml = unit_yz.Length > 8 ? unit_yz.Substring(0, 8) + "..." : unit_yz ;
                    divOwnUnitTitle = unit_yz;
                }
                string  unit_JL= ProjectService.getProjectUnitNameByUnitType(project.ProjectId, Const.ProjectUnitType_3);
                if (!string.IsNullOrEmpty(unit_JL))
                {
                    this.divJLUnit.InnerHtml = unit_JL.Length > 8 ? unit_JL.Substring(0, 8) + "..." : unit_JL;
                    divJLUnitTitle = unit_JL;
                }

                string unit_FB = ProjectService.getProjectUnitNameByUnitType(project.ProjectId, Const.ProjectUnitType_2);
                if (!string.IsNullOrEmpty(unit_FB))
                {
                    this.divSGUnit.InnerHtml = unit_FB.Length > 8 ? unit_FB.Substring(0, 8)+"..." : unit_FB + "...";
                }

                var getSGName = from x in Funs.DB.Project_ProjectUnit
                                join y in Funs.DB.Base_Unit on x.UnitId equals y.UnitId
                                where x.ProjectId == project.ProjectId && x.UnitType == Const.ProjectUnitType_2
                                select y.UnitName;
                foreach (var item in getSGName)
                {
                    divSGUnitTitle += item + ",";
                }
                this.divProjectMoney.InnerHtml = divProjectMoneyTitle = project.ProjectMoney.ToString();
                if (project.EndDate.HasValue)
                {
                    this.divEndDate.InnerHtml = string.Format("{0:yyyy-MM-dd}", project.EndDate);
                    int endDays = (project.EndDate.Value - DateTime.Now).Days;
                    if (endDays >= 0)
                    {
                        this.divRemainingDays.InnerHtml = endDays.ToString();
                    }
                    if (project.StartDate.HasValue)
                    {
                        int pdays = (project.EndDate.Value - project.StartDate.Value).Days;
                        if (pdays >= 0)
                        {
                            this.divProjectDays.InnerHtml = pdays.ToString();
                        }
                    }
                }

                var getImag = Funs.DB.AttachFile.FirstOrDefault(x => x.ToKeyId == project.ProjectId);
                if (getImag != null && !string.IsNullOrEmpty(getImag.AttachUrl))
                {
                    string url = getImag.AttachUrl.Replace('\\', '/');
                    string firtstUrl = Funs.GetStrListByStr(url, ',').FirstOrDefault();
                    if (!string.IsNullOrEmpty(firtstUrl))
                    {
                        string atturl = Funs.RootPath + firtstUrl.Replace(';', ' ').Trim();
                        if (File.Exists(atturl))
                        {
                            divProjectImg = "../"+ firtstUrl.Replace(';', ' ').Trim();
                        }
                    }
                }
            }
        }
        #endregion

        #region 获取质量问题
        ///整改率
        protected double CRectificationRate;
        ///合格率
        protected double CQualifiedRate;
        /// 焊接一次合格率
        protected double FirstPassRate;
        /// <summary>
        ///  获取质量问题
        /// </summary>
        private void getCQMSProblem()
        {            
            CRectificationRate = 0;            
            CQualifiedRate = 0;          
            FirstPassRate = 0;
            var getJointCheckDetail = from x in Funs.DB.Check_JointCheckDetail
                                      join y in Funs.DB.Check_JointCheck on x.JointCheckId equals y.JointCheckId
                                      where y.ProjectId == this.ProjectId
                                      select x;
            var getCheckControl = from x in Funs.DB.Check_CheckControl
                                  where x.ProjectId == this.ProjectId
                                  select x;
            ///问题总数
            int AllCount = getJointCheckDetail.Count() + getCheckControl.Count();
            this.divCQMSAllNum.InnerHtml = AllCount.ToString();
            if (AllCount > 0)
            {
                ///问题完成数
                var getJOk = getJointCheckDetail.Where(x => x.State == "6").Count();
                var getCOk = getCheckControl.Where(x => x.State == "7").Count();
                int CCount = getJOk + getCOk;
                this.divCQMSCAllNum.InnerHtml = CCount.ToString();
                this.divCQMSUCAllNum.InnerHtml = (AllCount - CCount).ToString();
                if (CCount > 0)
                {
                    CRectificationRate = Math.Round(CCount * 1.0 / AllCount * 100, 1);
                }
            }

            //var getSpotCheckDetail = from x in Funs.DB.Check_SpotCheckDetail
            //                        // join z in Funs.DB.Check_SpotCheck on x.SpotCheckCode equals z.SpotCheckCode
            //                         join y in Funs.DB.WBS_ControlItemAndCycle on x.ControlItemAndCycleId equals y.ControlItemAndCycleId
            //                         where y.ProjectId == this.ProjectId && x.IsOK != null
            //                         && y.ControlPoint != "C" && y.ControlPoint != "CR"
            //                         //&& z.ProjectId == this.ProjectId
            //                         select x;
            //int AllSpotCount = getSpotCheckDetail.Count();
            //if (AllSpotCount > 0)
            //{
            //    int okSpotCount = getSpotCheckDetail.Where(x => x.IsOK == true).Count();
            //    if (okSpotCount > 0)
            //    {
            //        CQualifiedRate = Math.Round(okSpotCount * 1.0 / AllSpotCount * 100, 1);
            //    }
            //}

            var inspectionManagements = from x in Funs.DB.View_CQMS_InspectionManagementDetail where x.ProjectId == this.ProjectId select x;
            if (inspectionManagements.Count() > 0)
            {
                int okInspectionManagements = inspectionManagements.Where(x => x.IsOnceQualified == true).Count();
                if (okInspectionManagements > 0)
                {
                    CQualifiedRate = Math.Round(okInspectionManagements * 1.0 / inspectionManagements.Count() * 100, 1);
                }
            }

            ///焊接一次合格率
            var getJots = from x in Funs.DB.HJGL_Batch_NDEItem
                          join y in Funs.DB.HJGL_Batch_BatchTrustItem on x.TrustBatchItemId equals y.TrustBatchItemId
                          join z in Funs.DB.HJGL_Batch_PointBatchItem on y.PointBatchItemId equals z.PointBatchItemId
                          join a in Funs.DB.HJGL_Batch_NDE on x.NDEID equals a.NDEID
                          where z.PointDate != null && z.PointState == "1" && y.RepairRecordId == null
                          && a.ProjectId == this.ProjectId
                          select x;
            int allHJCount = getJots.Count();
            if (allHJCount > 0)
            {
                var getOk = getJots.Where(x => x.CheckResult == "1");
                int okHJCount = getOk.Count();
                if (okHJCount > 0)
                {
                    FirstPassRate = Math.Round(okHJCount * 1.0 / allHJCount * 100, 1);
                }
            }            
        }
        #endregion

        #region 产值统计
        protected string SubUnitNames;
        protected string OutputValues;
        private void getOutputValues()
        {
            SubUnitNames = "[]";
            OutputValues = "[]";
            List<string> UnitNameList = new List<string>();
            List<int> OutputValueList = new List<int>();
            var getUnits = from x in Funs.DB.Project_ProjectUnit
                           join y in Funs.DB.Base_Unit on x.UnitId equals y.UnitId
                           where x.ProjectId == this.ProjectId && (x.UnitType == Const.ProjectUnitType_2 || x.UnitType == Const.ProjectUnitType_6)
                           select new { x.UnitId, y.ShortUnitName };
            if (getUnits.Count() > 0)
            {
                Random ro = new Random();
                foreach (var item in getUnits)
                {
                    UnitNameList.Add(item.ShortUnitName ?? " ");
                    int OutputValue = ro.Next(100);////获取分包单位产值
                    OutputValueList.Add(OutputValue);
                }
            }
            else
            {
                UnitNameList.Add(" ");
                OutputValueList.Add(0);
            }
            SubUnitNames = JsonConvert.SerializeObject(UnitNameList);
            OutputValues = JsonConvert.SerializeObject(OutputValueList);
        }
        #endregion

        /// <summary>
        /// 获取天气
        /// </summary>
        private void getWeatherValues()
        {
            var getW = WeatherService.GetWeather(this.ProjectId);
            if (getW != null)
            {
                this.divInfo.InnerHtml = getW.WeatherRef;
                this.divTEMP.InnerHtml = getW.AllTem;
                this.divHJ1.InnerHtml = getW.CurrTem;
                this.divHJ3.InnerHtml = getW.Humidity;
                this.divHJ5.InnerHtml = getW.Power;

                this.divHJ4.InnerHtml = getW.Aqi;
                this.divHJ6.InnerHtml = getW.Aqi;
            }
        }
    }
}