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

namespace FineUIPro.Web.common
{
    public partial class mainProjects : 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();
                /// 获取风险管控
                getHazard();
            }
        }

        #region  待办事项
        protected string swiper_One
        {
            get
            {
                var getDataList = Funs.DB.Sp_APP_GetToDoItems(this.CurrUser.LoginProjectId, CurrUser.UserId).ToList();
                string strNoticeHtml = string.Empty;
                foreach (var item in getDataList)
                {
                    string url = item.PCUrl;
                    strNoticeHtml += "<li data-id=\"" + url + "\" notice-id=\"" + item.DataId + "\" class=\"c-item swiper-slide\"><div class=\"tit\" title=\"" + item.MenuName + "\"><div class=\"flex\" ><div class=\"tit-t flex1\">" + item.MenuName + "</div><div class=\"tit-v\">" + string.Format("{0:yyyy-MM-dd}", item.DataTime) + "</div></div></div></li>";
                }
                return "<ul class=\"content-ul swiper-wrapper\">" + strNoticeHtml + "</ul>";
            }
        }
        #endregion

        #region 安全人工时
        /// <summary>
        /// 获取安全人工时
        /// </summary>
        private void getPersonWorkTime()
        {
            this.divSafeWorkTime.InnerHtml = "0000000000";
            var getMax = from x in Funs.DB.SitePerson_DayReportDetail
                         join y in Funs.DB.SitePerson_DayReport on x.DayReportId equals y.DayReportId
                         where y.ProjectId == this.CurrUser.LoginProjectId
                         select x;
            int wHours = 0;
            if (getMax.Count() > 0)
            {
                wHours = Convert.ToInt32(getMax.Sum(x => x.PersonWorkTime) ?? 0);
            }
            if (wHours > 0)
            {
                this.divSafeWorkTime.InnerHtml = ((wHours % 100000000) / 10000000).ToString() + ((wHours % 10000000) / 1000000).ToString() + ((wHours % 1000000) / 100000).ToString()
                     + ((wHours % 100000) / 10000).ToString() + ((wHours % 10000) / 1000).ToString() + ((wHours % 1000) / 100).ToString() + ((wHours % 100) / 10).ToString() + (wHours % 10).ToString();
            }

            ///整改单          
            var getRectify = from x in Funs.DB.Check_RectifyNotices
                             where x.ProjectId == this.ProjectId && x.States != Const.State_0 && x.States != null
                             select x;
            int allcout = getRectify.Count();
            if (allcout > 0)
            {
                this.divAllRectify.InnerHtml = allcout.ToString();
                int ccount = getRectify.Where(x => x.States == Const.State_5).Count();
                this.divCRectify.InnerHtml = ccount.ToString();
                this.divUCRectify.InnerHtml = (allcout - ccount).ToString();
            }
        }
        #endregion

        #region 劳务统计
        protected string WorkPostS;
        protected string InPostCounts;
        protected string InDutyCounts;
        /// <summary>
        ///  劳务统计
        /// </summary>
        private void getSitePerson()
        {
            int AllCount = 0;
            int MCount = 0;
            //var getallin = APIPageDataService.getPersonInOutNum(this.ProjectId, DateTime.Now.AddDays(-1));
            DateTime dateValue = DateTime.Now.AddDays(-1);
            List<Model.PageDataPersonInOutItem> getallin = new List<Model.PageDataPersonInOutItem>();
            var getInMaxs = from x in Funs.DB.SitePerson_Person
                            join y in Funs.DB.Base_WorkPost on x.WorkPostId equals y.WorkPostId
                            where x.ProjectId == this.CurrUser.LoginProjectId && x.IsUsed == true
                            select new Model.PageDataPersonInOutItem
                            {
                                PersonId = x.PersonId,
                                PostType = y.PostType,
                                WorkPostId = x.WorkPostId,
                            };
            if (getInMaxs.Count() > 0)
            {
                getallin = getInMaxs.Distinct().ToList();
            }
            AllCount = getallin.Count();
            if (AllCount > 0)
            {
                this.divALLPerson.InnerHtml = AllCount.ToString();
                MCount = getallin.Where(x => x.PostType == Const.PostType_1).Count();
                /////管理人数
                this.divGLPerson.InnerHtml = MCount.ToString();
                /////作业人数
                this.divZYPerson.InnerHtml = (AllCount - MCount).ToString();
            }

            WorkPostS = "[]";
            InPostCounts = "[]";
            InDutyCounts = "[]";
            List<int> InPostCountList = new List<int>();
            List<int> InDutyCountList = new List<int>();
            List<string> worksList = new List<string>();
            //if (this.CurrUser.UserId != Const.hfnbdId)
            //{
            var getPersons = Funs.DB.SitePerson_Person.Where(x => x.ProjectId == this.ProjectId && x.IsUsed == true && 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/indexv2/assets/image/index6/center-bg.jpeg";
            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()+ "<span>天</span>";
                    }
                    if (project.StartDate.HasValue)
                    {
                        int pdays = (project.EndDate.Value - project.StartDate.Value).Days;
                        if (pdays >= 0)
                        {
                            this.divProjectDays.InnerHtml = pdays.ToString()+ "<span>个</span>";
                        }
                    }
                }

                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.ProcessControl_InspectionManagement 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
                           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;
            }
        }

        #region 风险管控
        protected string riskData1;
        protected string riskData2;
        protected string riskData3;
        protected string riskData4;
        /// <summary>
        /// 获取风险管控
        /// </summary>
        private void getHazard()
        {
            var getHazards = from x in Funs.DB.Hazard_HazardSelectedItem
                             join y in Funs.DB.Base_RiskLevel on x.HazardLevel equals y.RiskLevelId
                             where x.ProjectId == this.ProjectId
                             select new { x.HazardSelectedItemId, y.RiskLevel };
            riskData1 = getHazards.Count(x => x.RiskLevel == 1).ToString();
            riskData2 = getHazards.Count(x => x.RiskLevel == 2).ToString();
            riskData3 = getHazards.Count(x => x.RiskLevel == 3).ToString();
            riskData4 = getHazards.Count(x => x.RiskLevel == 4).ToString();
        }
        #endregion
    }
}