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.WebApi.Models;

namespace APT.SC.WebApi.Controllers.Api.BI
{
    /// <summary>
    ///  年度监测汇总
    /// </summary>
    [Route("api/PP/BIController")]
    [TypeFilter(typeof(CustomActionFilterAttribute))]
    public class BIController : AuthorizeApiController<T_FM_BASE_CONFIG>
    {
        /// <summary>
        /// 提取安全任务完成分析数据
        /// </summary>
        /// <param name="pageFilter">更新超时时间</param>
        /// <returns></returns>
        [HttpPost, Route("updateSafeTaskData")]
        public JsonActionResult<bool> updateSafeTaskData([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var param = GetEntity<T_FM_SYNC_TASK>(t => t.CODE == "BI001");
                param.SYNC_PARAM = DateTime.Now.AddMonths(-3).ToShortDateString();
                UpdateEntity(param);
                BaseFilter basefilter1 = new BaseFilter(filter.GetOrgId());
                basefilter1.SelectField = new string[] { "ID" };
                BaseFilter basefilter2 = new BaseFilter(filter.GetOrgId());
                basefilter2.SelectField = new string[] { "SOURCE_DATA_ID" };
                var allnoticeTask = GetEntities<T_FM_NOTIFICATION_TASK>(t => t.NOTICE_STATUS == 2 && t.CREATE_TIME > DateTime.Parse(param.SYNC_PARAM), basefilter2);
                List<T_FO_PRE_SHIFT_MEETING_RECORD> fo01s = new List<T_FO_PRE_SHIFT_MEETING_RECORD>();
                List<T_FO_CURRENT_CLASS_RECORD> fo02s = new List<T_FO_CURRENT_CLASS_RECORD>();
                List<T_FO_CHANGE_SHIFT_RECORD> fo03s = new List<T_FO_CHANGE_SHIFT_RECORD>();
                List<T_FO_TEAM_ACTIVITY> fo04s = new List<T_FO_TEAM_ACTIVITY>();

                var fo01 = GetEntities<T_FO_PRE_SHIFT_MEETING_RECORD>(t => t.PRE_MEETING_STATUS == FOPreMeetingStatusEnum.归档 && t.OVERTIME == FOISOVERTIME.未统计, basefilter1);
                foreach (var item in fo01)
                {
                    var isOver = allnoticeTask.Where(t => t.SOURCE_DATA_ID == item.ID);
                    if (isOver.Any())
                    {
                        item.OVERTIME = FOISOVERTIME.超时;
                    }
                    else
                    {
                        item.OVERTIME = FOISOVERTIME.未超时;
                    }
                    fo01s.Add(item);
                }
                BantchUpdateEntity(fo01s, "OVERTIME");
                var fo02 = GetEntities<T_FO_CURRENT_CLASS_RECORD>(t => t.SHIFT_STATUS == (int)FOShiftStatusEnum.归档 && t.OVERTIME == FOISOVERTIME.未统计, basefilter1);
                foreach (var item in fo02)
                {
                    var isOver = allnoticeTask.Where(t => t.SOURCE_DATA_ID == item.ID);
                    if (isOver.Any())
                    {
                        item.OVERTIME = FOISOVERTIME.超时;
                    }
                    else
                    {
                        item.OVERTIME = FOISOVERTIME.未超时;
                    }
                    fo02s.Add(item);
                }
                BantchUpdateEntity(fo02s, "OVERTIME");
                var fo03 = GetEntities<T_FO_CHANGE_SHIFT_RECORD>(t => t.SHIFT_STATUS == (int)FOChangeShiftStatusEnum.归档 && t.OVERTIME == FOISOVERTIME.未统计, basefilter1);
                foreach (var item in fo03)
                {
                    var isOver = allnoticeTask.Where(t => t.SOURCE_DATA_ID == item.ID);
                    if (isOver.Any())
                    {
                        item.OVERTIME = FOISOVERTIME.超时;
                    }
                    else
                    {
                        item.OVERTIME = FOISOVERTIME.未超时;
                    }
                    fo03s.Add(item);
                }
                BantchUpdateEntity(fo03s, "OVERTIME");
                var fo04 = GetEntities<T_FO_TEAM_ACTIVITY>(t => t.TA_STATUS == (int)FOTeamActivityState.已归档 && t.OVERTIME == FOISOVERTIME.未统计, basefilter1);
                foreach (var item in fo04)
                {
                    var isOver = allnoticeTask.Where(t => t.SOURCE_DATA_ID == item.ID);
                    if (isOver.Any())
                    {
                        item.OVERTIME = FOISOVERTIME.超时;
                    }
                    else
                    {
                        item.OVERTIME = FOISOVERTIME.未超时;
                    }
                    fo04s.Add(item);
                }
                BantchUpdateEntity(fo04s, "OVERTIME");

                DeleteEntity<T_BI_SAFETASK_FINISH>(t => true);
                BaseFilter baseFilter = new BaseFilter(filter.GetOrgId());
                baseFilter.Include = new string[] { "Nav_Department.Nav_Parent.Nav_Parent", "Nav_ChargePerson" };
                var allTeams = GetEntities<T_FM_TEAM>(t => t.IS_DELETED == false&&t.ENABLE_STATUS==0&&t.CHARGE_PERSON_ID!=null, baseFilter);
                List<T_BI_SAFETASK_FINISH> biSafeFinishs = new List<T_BI_SAFETASK_FINISH>();
                var selectFilter = new BaseFilter(filter.GetOrgId());
                foreach (var team in allTeams)
                {
                    var filterTime = new DateTime[] { DateTime.Now.AddDays(-7), DateTime.Now.AddMonths(-1), DateTime.Now.AddMonths(-3), DateTime.Now.AddMonths(-6), DateTime.Now.AddMonths(-12), DateTime.Now.AddYears(-10) };
                    for (int i = 0; i < filterTime.Length; i++)
                    {
                        var biSafeFinish = new T_BI_SAFETASK_FINISH();
                        biSafeFinish.ORG_ID = filter.GetOrgId();
                        biSafeFinish.TEAM_ID = team.ID;
                        biSafeFinish.TEAM_NAME = team.NAME;
                        biSafeFinish.TEAM_CHARGE_USER = team.Nav_ChargePerson.NAME;
                        biSafeFinish.DEPARTMENT_NAME = team.Nav_Department.Nav_Parent.Nav_Parent.NAME;
                        selectFilter.SelectField = new string[] { "ID", "PRE_MEETING_STATUS", "OVERTIME" };
                        var fo01a = GetEntities<T_FO_PRE_SHIFT_MEETING_RECORD>(t => t.TEAM_ID == team.ID && t.MEETING_TIME > filterTime[i], selectFilter);
                        biSafeFinish.FO01_TOTAL = fo01a.Count();
                        biSafeFinish.FO01_FINISH = fo01a.Count(t => t.PRE_MEETING_STATUS == FOPreMeetingStatusEnum.归档 && t.OVERTIME != FOISOVERTIME.超时);
                        biSafeFinish.FO01_UNFINISH = fo01a.Count(t => t.PRE_MEETING_STATUS < FOPreMeetingStatusEnum.归档);
                        biSafeFinish.FO01_OVERTIME = fo01a.Count(t => t.OVERTIME == FOISOVERTIME.超时);
                        selectFilter.SelectField = new string[] { "ID", "SHIFT_STATUS", "OVERTIME" };
                        var fo02a = GetEntities<T_FO_CURRENT_CLASS_RECORD>(t => t.CLASS_TEAM_ID == team.ID && t.RECORD_DATE > filterTime[i], selectFilter);
                        biSafeFinish.FO02_TOTAL = fo02a.Count();
                        biSafeFinish.FO02_FINISH = fo02a.Count(t => t.SHIFT_STATUS == (int)FOShiftStatusEnum.归档 && t.OVERTIME != FOISOVERTIME.超时);
                        biSafeFinish.FO02_UNFINISH = fo02a.Count(t => t.SHIFT_STATUS < (int)FOShiftStatusEnum.归档);
                        biSafeFinish.FO02_OVERTIME = fo02a.Count(t => t.OVERTIME == FOISOVERTIME.超时);
                        selectFilter.SelectField = new string[] { "ID", "SHIFT_STATUS", "OVERTIME" };
                        var fo03a = GetEntities<T_FO_CHANGE_SHIFT_RECORD>(t => t.TEAM_ID == team.ID && t.CHANGE_SHIFT_TIME > filterTime[i], selectFilter);
                        biSafeFinish.FO03_TOTAL = fo03a.Count();
                        biSafeFinish.FO03_FINISH = fo03a.Count(t => t.SHIFT_STATUS == (int)FOChangeShiftStatusEnum.归档 && t.OVERTIME != FOISOVERTIME.超时);
                        biSafeFinish.FO03_UNFINISH = fo03a.Count(t => t.SHIFT_STATUS < (int)FOChangeShiftStatusEnum.归档);
                        biSafeFinish.FO03_OVERTIME = fo03a.Count(t => t.OVERTIME == FOISOVERTIME.超时);
                        selectFilter.SelectField = new string[] { "ID", "TA_STATUS", "OVERTIME" };
                        var fo04a = GetEntities<T_FO_TEAM_ACTIVITY>(t => t.TEAM_ID == team.ID && t.ACTIVITY_TIME > filterTime[i], selectFilter);
                        biSafeFinish.FO04_TOTAL = fo04a.Count();
                        biSafeFinish.FO04_FINISH = fo04a.Count(t => t.TA_STATUS == (int)FOTeamActivityState.已归档 && t.OVERTIME != FOISOVERTIME.超时);
                        biSafeFinish.FO04_UNFINISH = fo04a.Count(t => t.TA_STATUS < (int)FOTeamActivityState.已归档);
                        biSafeFinish.FO04_OVERTIME = fo04a.Count(t => t.OVERTIME == FOISOVERTIME.超时);
                        biSafeFinish.ENDTIME = DateTime.Now;
                        biSafeFinish.STARTTIME = filterTime[i];
                        if (i == 0)
                        {
                            biSafeFinish.FILTER_TIME = FilterTimeType.LastWeek;
                        }
                        else if (i == 1)
                        {
                            biSafeFinish.FILTER_TIME = FilterTimeType.LastMonth;
                        }
                        else if (i == 2)
                        {
                            biSafeFinish.FILTER_TIME = FilterTimeType.LastThreeMonth;
                        }
                        else if (i == 3)
                        {
                            biSafeFinish.FILTER_TIME = FilterTimeType.LastHalfYear;
                        }
                        else if (i == 4)
                        {
                            biSafeFinish.FILTER_TIME = FilterTimeType.LastYear;
                        }
                        else if (i == 5)
                        {
                            biSafeFinish.FILTER_TIME = 0;
                        }
                        biSafeFinishs.Add(biSafeFinish);
                    }
                }
                UnifiedCommit(() =>
                {
                    if (biSafeFinishs.Any())
                        BantchAddEntityNoCommit(biSafeFinishs);
                });
                return true;
            });
        }
        /// <summary>
        /// 用户登录统计分析
        /// </summary>
        /// <param name="pageFilter">用户登录统计分析</param>
        /// <returns></returns>
        [HttpPost, Route("updateUserLogin")]
        public JsonActionResult<bool> updateUserLogin([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {

                var dtnow = DateTime.Now;
                if (filter.Parameter1 != null)
                {
                    dtnow = DateTime.Parse(filter.Parameter1);
                }
                //dtnow = dtnow.AddDays(-10);
                //for (int i = 0; i < 11; i++)
                //{
                //var dtnow1 = dtnow.AddDays(i);
                DateTime maxDate = dtnow.Date;
                DateTime minDate = dtnow.AddDays(-3).Date;

                var allLoginRecord = GetEntities<T_BI_LOGIN_RECORD>(t => t.CREATE_TIME > minDate && t.CREATE_TIME < maxDate, new BaseFilter(filter.GetOrgId())).Select(t => new { t.USER_ID, ((DateTime)t.CREATE_TIME).Date });
                var alldistinctUser = allLoginRecord.Select(t => t.USER_ID).Distinct();
                int count = 0;
                foreach (var user in alldistinctUser)
                {
                    var d1 = allLoginRecord.Where(t => t.USER_ID == user && t.Date == maxDate.Date.AddDays(-1));
                    var d2 = allLoginRecord.Where(t => t.USER_ID == user && t.Date == maxDate.Date.AddDays(-2));
                    var d3 = allLoginRecord.Where(t => t.USER_ID == user && t.Date == maxDate.Date.AddDays(-3));
                    if (d1.Any() && d2.Any() && d3.Any())
                    {
                        count++;
                    }
                }

                T_BI_ACTIVE_USER_RECORD activeUserCount = new T_BI_ACTIVE_USER_RECORD
                {
                    COUNT = count,
                    DATE = maxDate.AddDays(-1),
                    ORG_ID = filter.GetOrgId(),
                    type = 0
                };
                T_BI_ACTIVE_USER_RECORD LoginUserCount = new T_BI_ACTIVE_USER_RECORD
                {
                    COUNT = allLoginRecord.Where(t => t.Date == maxDate.AddDays(-1)).Distinct(t => t.USER_ID).Count(),
                    DATE = maxDate.AddDays(-1),
                    ORG_ID = filter.GetOrgId(),
                    type = 1
                };
                UnifiedCommit(() =>
                {
                    DeleteEntityNoCommit<T_BI_ACTIVE_USER_RECORD>(t => t.DATE == maxDate.AddDays(-1));
                    AddEntityNoCommit(activeUserCount);
                    AddEntityNoCommit(LoginUserCount);
                });
                //}


                return true;
            });
        }

        /// <summary>
        /// 定期短信发送
        /// </summary>
        /// <param name="pageFilter">定期短信发送</param>
        /// <returns></returns>
        [HttpPost, Route("regularSendSMS")]
        public JsonActionResult<bool> regularSendSMS([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                DateTime now = DateTime.Now;
                var allUsers = GetEntities<T_FM_USER>(t => t.ENABLE_STATUS == 0, new BaseFilter(filter.GetOrgId()));
                var approveUsers = GetEntities<T_FM_USER>(t => t.Nav_Department.DEPARTMENT_TYPE != 2 && t.ENABLE_STATUS == 0, new BaseFilter(filter.GetOrgId()));
                var userIds = approveUsers.Select(t => t.ID);
                List<T_FM_NOTIFICATION_TASK> sendSMSs = null;
                if (now.Hour >= 7 && now.Hour < 23)
                {
                    sendSMSs = GetEntities<T_FM_NOTIFICATION_TASK>(t => t.NOTICE_STATUS == 0 && t.CREATE_TIME > now.AddDays(-6) && !t.SOURCE_FORMCODE.Contains("FO005") && t.SENDTIME == DateTime.MinValue, new BaseFilter(filter.GetOrgId())).ToList();
                    var sendSMSs2 = sendSMSs.Where(t => t.TASK_ENDDT < now.AddHours(1) && t.TASK_ENDDT > t.TASK_STARTDT);
                    foreach (var send in sendSMSs2)
                    {
                        List<string> phoneNumbers = new List<string>();
                        List<string> templates = new List<string>();
                        var user = allUsers.FirstOrDefault(t => t.ID == send.USER_ID);
                        if (user != null && user.PHONE != null)
                        {
                            send.SENDTIME = DateTime.Now;
                            phoneNumbers.Add(user.PHONE);
                            templates.Add(send.NOTICE_TITLE);
                            templates.Add(send.TASK_ENDDT.ToString());
                            TencentSendSMS tencentSendSMS = new TencentSendSMS();
                            var result = tencentSendSMS.sendSMS("1747259", phoneNumbers.ToArray(), templates.ToArray());
                            if (result.SendStatusSet[0].Code.Equals("Ok"))
                            {
                                UnifiedCommit(() =>
                                {
                                    UpdateEntityNoCommit(send);
                                });
                            }
                        }
                    }
                    //&& t.NOTICE_TITLE.Contains("审批")
                    var sendSMSs1 = sendSMSs.Where(t => userIds.Contains(t.USER_ID) && t.CREATE_TIME > now.AddHours(-8));
                    foreach (var send in sendSMSs1)
                    {
                        List<string> phoneNumbers = new List<string>();
                        List<string> templates = new List<string>();
                        var user = approveUsers.FirstOrDefault(t => t.ID == send.USER_ID);
                        if (user != null && user.PHONE != null)
                        {
                            send.SENDTIME = DateTime.Now;
                            phoneNumbers.Add(user.PHONE);
                            templates.Add(send.NOTICE_TITLE);
                            templates.Add(send.TASK_ENDDT.ToString());
                            TencentSendSMS tencentSendSMS = new TencentSendSMS();
                            var result = tencentSendSMS.sendSMS("1747261", phoneNumbers.ToArray(), templates.ToArray());
                            if (result.SendStatusSet[0].Code.Equals("Ok"))
                            {
                                UnifiedCommit(() =>
                                {
                                    UpdateEntityNoCommit(send);
                                });
                            }
                        }
                    }

                }
                return true;
            });
        }
    }
}
