using APT.BaseData.Domain.Entities.FM;
using APT.BaseData.Domain.IServices;
using APT.Infrastructure.Api;
using APT.Infrastructure.Core;
using APT.MS.Domain.Entities.BI;
using APT.MS.Domain.Entities.BS;
using APT.MS.Domain.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static APT.MS.Domain.Enums.BI.BIEnums;

namespace APT.BaseData.Services.DomainServices
//namespace APT.BaseData.Services.Services.BI
{
    /// <summary>
    /// 安全检查情况综合统计分析
    /// 业务数据抽取 保存到表单
    /// </summary>
    public partial class BIBSSafeCheckService : CommonService, IBIBSSafeCheckService
    {
        public BIBSSafeCheckService(IRepository repository)
            : base(repository)
        {
        }

        #region 安全检查情况综合统计分析

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ORG_ID"></param>
        /// <param name="dtRun"></param>
        /// <param name="listSafeCheck"></param>
        /// <param name="listCheckType"></param>
        /// <param name="listSummary"></param>
        /// <param name="modelLog"></param>
        /// <returns></returns>
        public bool SafeCheckGet(Guid ORG_ID, DateTime? dtRun, ref List<T_BI_BSSAFECHECK> listSafeCheck, ref List<T_BI_BSCHECKTYPE> listCheckType, ref List<T_BI_SUMMARY> listSummary, ref T_BI_RUNLOG modelLog)
        {
            //统计时间
            if (!dtRun.HasValue)
                dtRun = DateTime.Now;
            DateTime? dtMin = null;
            DateTime dtNow = DateTime.Now;
            string Code = "BI002_BSSAFECHECK"; //编码

            modelLog = GetEntity<T_BI_RUNLOG>(e => e.CODE == Code);
            #region     日志登记时间

            if (modelLog == null)
            {
                modelLog = new T_BI_RUNLOG();
                modelLog.ID = Guid.NewGuid();
                modelLog.IS_DELETED = false;
                modelLog.ORG_ID = ORG_ID;
                modelLog.CREATE_TIME = dtNow;
                //modelLog.ENTITY_ORG_TPYE =;
                //modelLog.FORM_ID =;
                //modelLog.FLOW_STATUS =;
                //modelLog.FLOW_SEND_STATUS =;
                //modelLog.FLOW_ID =;
                //modelLog.CREATER_ID =;
                //modelLog.MODIFIER_ID =;

            }
            modelLog.CODE = Code;
            modelLog.RUNDATETIME = dtRun.Value;
            modelLog.MODIFY_TIME = dtNow;

            #endregion

            //数据 删除后新增 T_BI_BSSAFECHECK T_BI_BSCHECKTYPE
            //数据 更新（新增或者修改） T_BI_SUMMARY
            //listSafeCheck = new List<T_BI_BSSAFECHECK>();
            //listCheckType = new List<T_BI_BSCHECKTYPE>();
            //listSummary = new List<T_BI_SUMMARY>();
            List<T_BI_BSSAFECHECK> listSafeCheckFiliter = null;//为了登记 数量的中间参数


            //三者时间对应
            List<FilterTimeType> listTimeType = new List<FilterTimeType>();
            List<DateTime> listStart = new List<DateTime>();
            List<DateTime> listEnd = new List<DateTime>();

            #region      获取类型对应起止时间

            listTimeType.Add(FilterTimeType.LastWeek);
            listTimeType.Add(FilterTimeType.LastMonth);
            listTimeType.Add(FilterTimeType.LastThreeMonth);
            listTimeType.Add(FilterTimeType.LastHalfYear);
            listTimeType.Add(FilterTimeType.LastYear);

            for (int i = 0; i < listTimeType.Count; i++)
            {
                listEnd.Add(dtRun.Value);
                switch (listTimeType[i])
                {
                    case FilterTimeType.LastWeek:
                        listStart.Add(dtRun.Value.AddDays(-7));
                        break;
                    case FilterTimeType.LastMonth:
                        listStart.Add(dtRun.Value.AddMonths(-1));
                        break;
                    case FilterTimeType.LastThreeMonth:
                        listStart.Add(dtRun.Value.AddMonths(-3));
                        break;
                    case FilterTimeType.LastHalfYear:
                        listStart.Add(dtRun.Value.AddMonths(-6));
                        break;
                    case FilterTimeType.LastYear:
                        dtMin = dtRun.Value.AddYears(-1);
                        listStart.Add(dtMin.Value);
                        break;
                    default:
                        break;
                }
            }
            #endregion

            //安全检查 按创建时间 最长时间获取
            var listSafeChecks = GetEntities<T_BS_SAFE_CHECK>(e => !e.IS_DELETED && e.CREATE_TIME.HasValue && e.CREATE_TIME >= dtMin && e.CREATE_TIME <= listEnd[0] && e.CHECKOBJECT.HasValue && e.CHECK_TYPE_ID.HasValue && e.DEPARTMENTID.HasValue);

            List<BSMineTypeEditEnum> listMineType = new List<BSMineTypeEditEnum>();
            #region 矿类型
            if (listSafeChecks != null && listSafeChecks.Any())
            {
                var listCheckOBJECT = listSafeChecks.Where(e => e.CHECKOBJECT.HasValue).Select(e => e.CHECKOBJECT).Distinct();
                foreach (var item in listCheckOBJECT)
                {
                    if (!listMineType.Contains((BSMineTypeEditEnum)item))
                    {
                        listMineType.Add((BSMineTypeEditEnum)item);
                    }
                }
            }
            else
            {
                listMineType.Add(BSMineTypeEditEnum.MineChoose);
                listMineType.Add(BSMineTypeEditEnum.Minelast);
                listMineType.Add(BSMineTypeEditEnum.Mine);
                listMineType.Add(BSMineTypeEditEnum.MineUnderground);
            }

            #endregion

            //List<T_FM_DEPARTMENT> listTeam = new List<T_FM_DEPARTMENT>();
            #region     班组  
            //List<Guid> listDepID = null;
            //if (listSafeChecks != null && listSafeChecks.Any())
            //{
            //    //FMDepartmentType 部门 = 0, 车间 = 1, 班组 = 2, 公司 = 3
            //    listDepID = listSafeChecks.Select(e => e.DEPARTMENTID.Value).Distinct().ToList();
            //    var listDep = GetEntities<T_FM_DEPARTMENT>(e => listDepID.Contains(e.ID) && e.DEPARTMENT_TYPE == 2).OrderBy(e => e.NAME);
            //    foreach (var item in listDep)
            //    {
            //        if (!listTeam.Contains(item))
            //        {
            //            listTeam.Add(item);
            //        }
            //    }
            //}

            //if (listDepID == null)
            //{
            //    //返回数据

            //}
            //else
            //{
            //    //计算

            //}

            #endregion

            #region   数据计算   

            DateTime? dtStart = null;
            DateTime? dtEnd = null;
            int CHECKOBJECT = 0;
            Guid TeamID = Guid.Empty;
            int COUNTPLAN = 0;
            int COUNTCHECK = 0;
            int COUNTCHECKOUTTIME = 0;
            string PERCENTCHECK = "0%";
            //时间类型
            T_BI_SUMMARY modelSummary = null;
            //IEnumerable<T_BS_CHECK_TYPE> checkTypes = null;
            #region     班组安全检查情况

            for (int i = 0; i < listMineType.Count; i++)
            {
                //矿类型
                CHECKOBJECT = (int)listMineType[i];

                List<T_FM_DEPARTMENT> listTeam = new List<T_FM_DEPARTMENT>();

                #region     班组  
                List<Guid> listDepID = null;
                if (listSafeChecks != null && listSafeChecks.Any())
                {
                    //FMDepartmentType 部门 = 0, 车间 = 1, 班组 = 2, 公司 = 3
                    listDepID = listSafeChecks.Where(e => e.CHECKOBJECT == CHECKOBJECT).Select(e => e.DEPARTMENTID.Value).Distinct().ToList();
                    var listDep = GetEntities<T_FM_DEPARTMENT>(e => listDepID.Contains(e.ID) && e.DEPARTMENT_TYPE == 2).OrderBy(e => e.NAME);
                    foreach (var item in listDep)
                    {
                        if (!listTeam.Contains(item))
                        {
                            listTeam.Add(item);
                        }
                    }
                }

                #endregion

                //检查类型
                var listPerType = listSafeChecks.Where(e => e.CHECKOBJECT.Value == CHECKOBJECT);//&& listDepID.Contains(e.DEPARTMENTID.Value)
                var listCheckTypeID = listPerType.Select(e => e.CHECK_TYPE_ID.Value).Distinct().ToList();
                //var checkTypes = this.GetEntities<T_BS_CHECK_TYPE>(e => listCheckTypeID.Contains(e.ID), null);
                var checkTypes = this.GetEntities<T_BS_CHECK_TYPE>(e => listCheckTypeID.Contains(e.ID));

                for (int j = 0; j < listTimeType.Count; j++)
                {
                    dtStart = listStart[j];
                    dtEnd = listEnd[j];

                    #region     安全检查情况占比

                    //安全检查情况占比
                    foreach (var item in checkTypes)
                    {
                        //var listTypeTime = listPerType.Select(e => e.CREATE_TIME >= dtStart && e.CREATE_TIME <= dtEnd && e.CHECK_TYPE_ID == item.ID);
                        var listTypeTime = listPerType.Where(e => e.CREATE_TIME >= dtStart && e.CREATE_TIME <= dtEnd && e.CHECK_TYPE_ID == item.ID);
                        listCheckType.Add(new T_BI_BSCHECKTYPE()
                        {
                            ID = Guid.NewGuid(),
                            TimeType = listTimeType[j],
                            MineType = listMineType[i],
                            CHECKTYPEID = item.ID,
                            name = item.NAME,
                            value = (listTypeTime == null || !listTypeTime.Any()) ? "0" : listTypeTime.Where(e => e.CHECK_TYPE_ID == item.ID).Count().ToString(),
                            IS_DELETED = false,
                            ORG_ID = ORG_ID,
                            //ENTITY_ORG_TPYE = ,
                            //FORM_ID = ,
                            //FLOW_STATUS = ,
                            //FLOW_SEND_STATUS = ,
                            //FLOW_ID = ,
                            CREATE_TIME = dtNow,
                            //MODIFY_TIME = ,
                            //CREATER_ID = ,
                            //MODIFIER_ID = ,
                        });
                    }


                    #endregion


                    listSafeCheckFiliter = new List<T_BI_BSSAFECHECK>();
                    //搜索条件时间类型
                    for (int k = 0; k < listTeam.Count; k++)
                    {
                        //小组
                        TeamID = listTeam[k].ID;
                        var listPer = listSafeChecks.Where(e => e.CREATE_TIME >= dtStart && e.CREATE_TIME <= dtEnd && e.CHECKOBJECT.HasValue && e.CHECKOBJECT.Value == CHECKOBJECT && e.DEPARTMENTID == TeamID);
                        if (listPer != null && listPer.Any())
                        {
                            COUNTPLAN = listPer.Count();
                            COUNTCHECKOUTTIME = listPer.Where(e => e.APPROVE_ID.HasValue && !e.ISFINISHINTTIME).Count();
                            //COUNTCHECK = listPer.Where(e => e.STATUCHECK == 0).Count();
                            COUNTCHECK = listPer.Where(e => e.APPROVE_ID.HasValue).Count();
                            PERCENTCHECK = decimal.Round(Convert.ToDecimal(100.0 * COUNTCHECK / COUNTPLAN), 2) + "%";//保留2位小数
                        }
                        else
                        {
                            COUNTPLAN = 0;
                            COUNTCHECK = 0;
                            COUNTCHECKOUTTIME = 0;
                            PERCENTCHECK = "0%";
                        }

                        listSafeCheckFiliter.Add(new T_BI_BSSAFECHECK()
                        {
                            ID = Guid.NewGuid(),
                            TimeType = listTimeType[j],
                            MineType = listMineType[i],
                            TEAMID = TeamID,
                            TEAMNAME = listTeam[k].NAME,
                            COUNTPLAN = COUNTPLAN,//计划检查
                            COUNTCHECK = COUNTCHECK,//检查
                            COUNTCHECKOUTTIME = COUNTCHECKOUTTIME,//超时完成
                            PERCENTCHECK = PERCENTCHECK,
                            IS_DELETED = false,
                            ORG_ID = ORG_ID,
                            //ENTITY_ORG_TPYE = ,
                            //FORM_ID = ,
                            //FLOW_STATUS = ,
                            //FLOW_SEND_STATUS = ,
                            //FLOW_ID = ,
                            CREATE_TIME = dtNow,
                            //MODIFY_TIME = ,
                            //CREATER_ID = ,
                            //MODIFIER_ID = ,

                        });
                    }

                    #region    数量统计  modelSummary

                    modelSummary = listSummary.FirstOrDefault(e => e.MineType == listMineType[i] && e.TimeType == listTimeType[j]);
                    if (modelSummary == null)
                    {
                        modelSummary = new T_BI_SUMMARY();
                        modelSummary.ID = Guid.NewGuid();
                        modelSummary.CODE = Code;
                        modelSummary.MineType = listMineType[i];
                        modelSummary.TimeType = listTimeType[j];
                        modelSummary.ORG_ID = ORG_ID;
                        modelSummary.IS_DELETED = false;
                        modelSummary.CREATE_TIME = dtNow;

                        modelSummary.Parameter1 = "计划检查数";
                        modelSummary.Parameter2 = "按时完成";
                        modelSummary.Parameter3 = "超时完成";
                        modelSummary.Parameter4 = "未完成数";
                        modelSummary.Parameter5 = dtStart.Value.ToString("yyyyMMdd") + " - " + dtEnd.Value.ToString("yyyyMMdd");

                        dtStart = listStart[j];
                        dtEnd = listEnd[j];

                    }
                    modelSummary.MODIFY_TIME = dtNow;
                    modelSummary.Count1 = 0;
                    modelSummary.Count2 = 0;
                    modelSummary.Count3 = 0;
                    modelSummary.Count4 = 0;
                    #endregion

                    //数据 计算
                    if (listSafeCheckFiliter.Count > 0)
                    {
                        foreach (var item in listSafeCheckFiliter)
                        {
                            modelSummary.Count1 += item.COUNTPLAN;//计划检查数
                            modelSummary.Count4 += (item.COUNTPLAN - item.COUNTCHECK);//未完成数
                            modelSummary.Count3 += item.COUNTCHECKOUTTIME;//超时完成
                        }
                        modelSummary.Count2 = modelSummary.Count1 - modelSummary.Count2 - modelSummary.Count4;//按时完成= 计划数-超时完成 -未完成

                        listSafeCheck.AddRange(listSafeCheckFiliter);//数据添加
                    }
                    listSummary.Add(modelSummary);//数据添加
                }
            }
            #endregion


            #endregion

            return true;
        }



        #endregion

    }
}