using APT.BaseData.Domain.Entities.FM;
using APT.Infrastructure.Core;
using Microsoft.AspNetCore.Mvc;
using APT.Infrastructure.Api;
using System.Collections.Generic;
using System.Linq.Expressions;
using System;
using System.Linq;
using APT.BaseData.Domain.ApiModel;
using Ubiety.Dns.Core;
using System.Security.AccessControl;
using APT.MS.Domain.Entities.FO;
using APT.BaseData.Domain.Entities;
using APT.MS.Domain.Enums;
using APT.MS.Domain.Entities.BI;
using static APT.MS.Domain.Enums.BI.BIEnums;
using NPOI.SS.Formula.Functions;
using APT.PP.WebApi.Controllers.Api.PP;
using APT.Utility;
using Google.Protobuf.WellKnownTypes;
using APT.MS.Domain.Entities.BS;
using APT.BaseData.Domain.Enums;
using APT.WebApi.Models;
using APT.BaseData.Domain.IServices.FM;

namespace APT.SC.WebApi.Controllers.Api.BI
{
    /// <summary>
    ///  首页图表
    /// </summary>
    [Route("api/PP/BIHome")]
    [TypeFilter(typeof(CustomActionFilterAttribute))]
    public class BIHomeController : AuthorizeApiController<T_BI_HRISK_COUNT>
    {

        IFMSyncLogDetailService SyncLogDetailService { get; set; }
        public BIHomeController(IFMSyncLogDetailService syncLogDetailService)
        {
            SyncLogDetailService = syncLogDetailService;
        }
        /// <summary>
        /// 首页安全检查相关 图表数据插入
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("InsertBIHomeSafe")]
        public JsonActionResult<bool> InsertBIHomeSafe([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                DateTime CURR_TASK_START_TIME = DateTime.Now;
                DateTime dtNow = DateTime.Now;
                int caculateMonth = 6;
                if (!string.IsNullOrEmpty(filter.Parameter1))
                {
                    if (filter.Parameter1.Contains("|") && filter.Parameter1.Contains("caculateMonth"))
                    {
                        var param = filter.Parameter1.Split("|");
                        foreach (var item in param)
                        {
                            if (string.IsNullOrEmpty(item))
                                continue;
                            if (item.Contains("caculateMonth"))
                            {
                                try
                                {
                                    caculateMonth = int.Parse(item.Split("=", StringSplitOptions.RemoveEmptyEntries)[1]); //接收来自页面的参数
                                }
                                catch { caculateMonth = 6; }
                            }
                            else
                            {
                                try
                                {
                                    dtNow = Convert.ToDateTime(item);  //接收来自页面的参数
                                }
                                catch { dtNow = DateTime.Now; }
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            //接收来自页面的参数
                            dtNow = Convert.ToDateTime(filter.Parameter1);
                        }
                        catch { dtNow = DateTime.Now; }
                    }
                }
                if (caculateMonth > 12)
                {
                    //最多计算1年
                    return false;
                }
                var task = GetEntity<T_FM_SYNC_TASK>(filter.Keyword);
                if (task != null)
                {
                    task.CURR_TASK_START_TIME = CURR_TASK_START_TIME;//上次同步结束时间
                    task.UPDATE_SUCCES_TIME = DateTime.Now;//上次同步结束时间
                    task.SYNC_PARAM = "";//清空参数
                }

                //计算 近6个月的数据 
                DateTime dtMin = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01 00:00:00")).AddMonths(-1 * caculateMonth);
                // T_BI_HRISKCHANGE_PEC 各部门隐患整改率
                // T_BI_HRISK_COUNT  各部门隐患数量
                // T_BI_HRISK_TOP 高频隐患

                List<T_BI_HRISKCHANGE_PEC> listChangePec = new List<T_BI_HRISKCHANGE_PEC>();
                List<T_BI_HRISK_COUNT> listRiskCount = new List<T_BI_HRISK_COUNT>();
                List<T_BI_HRISK_TOP> listRiskTop = new List<T_BI_HRISK_TOP>();

                Expression<Func<T_BI_HRISKCHANGE_PEC, bool>> expression = e => !e.IS_DELETED;
                if (dtMin.Year == dtNow.Year)
                {
                    expression = expression.And(e => e.YEAR == dtMin.Year && e.MONTH >= dtMin.Month);
                }
                else
                {
                    expression = expression.And(e => e.YEAR >= dtMin.Year);
                }
                List<T_BI_HRISKCHANGE_PEC> listChangePecOld = GetEntities<T_BI_HRISKCHANGE_PEC>(expression, null, null).ToList();

                #region     部门及下属组织 dicDepChi

                Dictionary<T_FM_DEPARTMENT, List<Guid>> dicDepChi = new Dictionary<T_FM_DEPARTMENT, List<Guid>>();
                //所有组织
                var listDepAll = GetEntities<T_FM_DEPARTMENT>(e => !e.IS_DELETED, null, null).OrderBy(e => e.DEPARTMENT_TYPE);

                List<T_FM_DEPARTMENT> listDep = new List<T_FM_DEPARTMENT>();//部门级别的组织
                foreach (var item in listDepAll)
                {
                    //FMDepartmentType 部门=0,  车间=1,   班组=2,  公司=3
                    if (item.DEPARTMENT_TYPE == 0)//&& item.DEPARTMENT_STATUS == 1FMDepartmentStatus  职能部门 = 0,  生产部门 = 1,  安全部门 = 2, 
                    {
                        listDep.Add(item);
                    }
                }

                foreach (var item in listDep)
                {
                    var dep1 = listDepAll.Where(e => e.PARENT_ID.HasValue && e.PARENT_ID == item.ID);
                    List<Guid> listItemVal = new List<Guid>();
                    if (dep1 != null && dep1.Any())
                    {
                        listItemVal = dep1.Select(e => e.ID).ToList();
                        var dep2 = listDepAll.Where(e => e.PARENT_ID.HasValue && listItemVal.Contains(e.PARENT_ID.Value));
                        if (dep2 != null && dep2.Any())
                        {
                            listItemVal.AddRange(dep2.Select(e => e.ID).ToList());
                        }
                    }
                    listItemVal.Add(item.ID);
                    dicDepChi.Add(item, listItemVal);
                }

                #endregion

                #region    部门隐患整改率

                var sub = GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => !e.IS_DELETED && e.DEPARTMENT_ID.HasValue && e.CREATE_TIME.HasValue && e.CREATE_TIME >= dtMin, null, null);

                DateTime dtSearchMin = dtMin;
                DateTime dtSearchMax = dtMin;
                for (int i = 0; i < caculateMonth; i++)
                {
                    dtSearchMin = dtMin.AddMonths(i);
                    dtSearchMax = dtMin.AddMonths(i + 1).AddSeconds(-1);

                    foreach (var item in dicDepChi)
                    {
                        T_BI_HRISKCHANGE_PEC model = listChangePecOld.FirstOrDefault(e => e.YEAR == dtSearchMin.Year && e.MONTH == dtSearchMin.Month && e.DEPARTMENT_ID == item.Key.ID);
                        if (model == null)
                        {
                            model = new T_BI_HRISKCHANGE_PEC();
                            model.ID = Guid.NewGuid();
                            model.ORG_ID = filter.OrgId;

                            model.DEPARTMENT_ID = item.Key.ID;
                            model.DEPARTMENT_NAME = item.Key.NAME;

                            model.YEAR = dtSearchMin.Year;
                            model.MONTH = dtSearchMin.Month;

                            model.YEARMONTH = model.YEAR + "年" + (model.MONTH > 9 ? model.MONTH : ("0" + model.MONTH)) + "月";
                            if (item.Key.MineType.HasValue)
                            {
                                model.MINETYPE = (FMProductionUnit)item.Key.MineType;
                            }
                            try
                            {
                                model.DEPARTMENT_TYPE = (FMDepartmentType)item.Key.DEPARTMENT_TYPE;
                            }
                            catch
                            {
                                model.DEPARTMENT_TYPE = FMDepartmentType.部门;
                            }
                        }
                        model.COUNT = 0;
                        model.COUNT_DEL = 0;


                        var SubMonth = sub.Where(e => dtSearchMin <= e.CREATE_TIME && e.CREATE_TIME <= dtSearchMax && item.Value.Contains(e.DEPARTMENT_ID.Value));
                        if (SubMonth != null && SubMonth.Any())
                        {
                            model.COUNT = SubMonth.Count();
                            foreach (var itemSub in SubMonth)
                            {
                                //RiskContentState.OK  if (itemSub.SUBMITFINISHTIME.HasValue)
                                if (itemSub.RiskContentState == 60 || itemSub.RiskContentState == 80)
                                {
                                    model.COUNT_DEL++;
                                }
                            }
                        }
                        listChangePec.Add(model);
                    }
                }

                foreach (var item in listChangePec)
                {
                    if (item.COUNT == 0 || item.COUNT_DEL == 0)
                    {
                        item.CHANGE_PERCENT = 0;
                        item.CHANGE_PERCENT_SHOW = "100.00%";//没有需要整改的
                    }
                    else
                    {
                        item.CHANGE_PERCENT = Math.Round(Convert.ToDecimal(100.0 * item.COUNT_DEL / item.COUNT), 2);
                        item.CHANGE_PERCENT_SHOW = item.CHANGE_PERCENT + "%";
                    }
                }

                #endregion


                #region    各部门隐患数量
                IEnumerable<T_BS_RISK_SUBMIT_CONTENT> subDep = null;
                var sub2 = GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => !e.IS_DELETED && e.DEPARTMENT_ID.HasValue && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == dtNow.Year, null, null);
                var listRiskCountOld = GetEntities<T_BI_HRISK_COUNT>(e => e.YEAR == dtNow.Year && !e.IS_DELETED, null, null);

                foreach (var item in dicDepChi)
                {
                    var riskCount = listRiskCountOld.FirstOrDefault(e => e.DEPARTMENT_ID.HasValue && !e.IS_DELETED && e.DEPARTMENT_ID.Value == item.Key.ID);
                    if (riskCount == null)
                    {
                        riskCount = new T_BI_HRISK_COUNT();
                        riskCount.ID = Guid.NewGuid();
                        riskCount.ORG_ID = filter.OrgId;
                        riskCount.YEAR = dtNow.Year;
                        try
                        {
                            riskCount.MINETYPE = item.Key.MineType.HasValue ? ((FMProductionUnit)item.Key.MineType.Value) : null;
                        }
                        catch { }
                        try
                        {
                            riskCount.DEPARTMENT_TYPE = FMDepartmentType.部门;
                        }
                        catch { }
                        riskCount.DEPARTMENT_ID = item.Key.ID;
                        riskCount.DEPARTMENT_NAME = item.Key.NAME;
                    }
                    riskCount.COUNT_CHANGE = 0;
                    riskCount.COUNT_UNCHANGE = 0;


                    subDep = sub2.Where(e => e.DEPARTMENT_ID.Value == item.Key.ID);
                    if (subDep != null && subDep.Any())
                    {
                        foreach (var itemSub in subDep)
                        {
                            if (itemSub.RiskContentState.HasValue && (itemSub.RiskContentState == 60 || itemSub.RiskContentState == 80))
                            {
                                riskCount.COUNT_CHANGE++;
                            }
                            else
                            {
                                riskCount.COUNT_UNCHANGE++;
                            }
                        }
                    }

                    listRiskCount.Add(riskCount);
                }

                #endregion

                #region    高频隐患 (先删后加)

                List<Guid> listTopID = new List<Guid>();
                var listRiskTopOld = GetEntities<T_BI_HRISK_TOP>(e => e.YEAR == dtNow.Year && !e.IS_DELETED, null, null);
                if (listRiskTopOld != null && listRiskTopOld.Any())
                {
                    listTopID = listRiskTopOld.Select(e => e.ID).ToList();
                }

                var listSubTop = GetEntities<T_BS_RISK_SUBMIT_CONTENT>(e => !e.IS_DELETED && e.DEPARTMENT_ID.HasValue && e.CREATE_TIME.HasValue && e.CREATE_TIME.Value.Year == dtNow.Year && e.CHECKCONTENT != null, null, null);

                Dictionary<string, int> dic = new Dictionary<string, int>();
                foreach (var item in listSubTop)
                {
                    if (dic.ContainsKey(item.CHECKCONTENT))
                    {
                        dic[item.CHECKCONTENT]++;
                    }
                    else
                    {
                        dic.Add(item.CHECKCONTENT, 1);
                    }
                }

                foreach (var item in dic)
                {
                    //全部先加 后面排序再删除
                    var riskTop = new T_BI_HRISK_TOP();
                    riskTop.ID = Guid.NewGuid();
                    riskTop.ORG_ID = filter.OrgId;
                    riskTop.DEPARTMENT_TYPE = FMDepartmentType.公司;
                    riskTop.DEPARTMENT_ID = Guid.Empty;
                    riskTop.MAINID = Guid.Empty;

                    riskTop.YEAR = dtNow.Year;
                    riskTop.CHECKCONTENT = item.Key;
                    riskTop.COUNT = item.Value;
                    listRiskTop.Add(riskTop);
                }

                if (listRiskTop.Count > 8)
                {
                    listRiskTop = listRiskTop.OrderByDescending(e => e.COUNT).ToList();
                    int count = listRiskTop.Count;
                    for (int i = 8; i < count; i++)
                    {
                        listRiskTop.RemoveAt(i - 1);
                        count--;
                        i--;
                    }
                }

                #endregion

                if (task != null)
                {
                    task.TASK_END_TIME = DateTime.Now;
                }

                this.UnifiedCommit(() =>
                {
                    if (task != null)
                        UpdateEntityNoCommit(task);
                    if (listChangePec.Count > 0)
                        BantchSaveEntityNoCommit(listChangePec);
                    if (listRiskCount.Count > 0)
                        BantchSaveEntityNoCommit(listRiskCount);
                    if (listRiskTop.Count > 0)
                        BantchSaveEntityNoCommit(listRiskTop);
                    if (listTopID.Count > 0)
                        BantchDeleteEntityNoCommit<T_BI_HRISK_TOP>(listTopID);
                });

                int Count = ((listChangePec != null && listChangePec.Any()) ? listChangePec.Count : 0) + ((listRiskCount != null && listRiskCount.Any()) ? listRiskCount.Count : 0) + ((listRiskTop != null && listRiskTop.Any()) ? listRiskTop.Count : 0) + ((listTopID != null && listTopID.Any()) ? listTopID.Count : 0);
                SyncLogDetailService.InsertSyncLogDetail(HttpContext.Items, HttpContext.TraceIdentifier, filter.OrgId, Count, filter.Parameter1, SyncLogType.BSCreateCheckPlanSet);

                return true;
            });
        }
    }
}
