using OASystem.API.OAMethodLib.ALiYun;
using OASystem.API.OAMethodLib.QiYeWeChatAPI;
using OASystem.API.OAMethodLib.QiYeWeChatAPI.AppNotice;
using OASystem.Domain.Dtos.Business;
using OASystem.Domain.Entities.Business;
using OASystem.Domain.Entities.Customer;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.ViewModels.CRM;
using OASystem.Domain.ViewModels.Groups;
using OASystem.Infrastructure.Repositories.Groups;

namespace OASystem.API.OAMethodLib.Quartz.Business
{
    public static class DeleReminderMessage
    {
        private readonly static DelegationInfoRepository _grpDeleRep = AutofacIocManager.Instance.GetService<DelegationInfoRepository>();
        private static readonly IQiYeWeChatApiService _qiYeWeChatApiService = AutofacIocManager.Instance.GetService<IQiYeWeChatApiService>();

        /// <summary>
        /// 检查团组结束日期,将当天和2天后的团组整理并发送短信提醒
        /// </summary>
        public static async void PostMessage()
        {
            DeleReminderConfig _deleReminderConfig = AutofacIocManager.Instance.GetService<DeleReminderConfig>();
            List<string> list_PhoneNumbers = _deleReminderConfig.PhoneNumber.Split(',').ToList();

            //sqladd2day查询0A2014数据库,正式使用新OA后将两次查询合并
            DateTime dtNow = DateTime.Now;
            string add2day = dtNow.AddDays(2).ToString("yyyy-MM-dd");
            string add7day = dtNow.AddDays(7).ToString("yyyy-MM-dd");

            _grpDeleRep.ChangeDataBase(DBEnum.OA2014DB);


            string sql = string.Format(@" Select * From DelegationInfo With(Nolock) Where IsDel=0 And VisitEndDate ='{0}' Or VisitStartDate='{1}' ", add2day, add7day);
            List<OA2021_DelegationInfo> list_source = _grpDeleRep._sqlSugar.SqlQueryable<OA2021_DelegationInfo>(sql).ToList();

            _grpDeleRep.ChangeDataBase(DBEnum.OA2023DB);
            if (list_source.Count > 0)
            {
                List<OA2021_DelegationInfo> listAdd7day = list_source.Where(s => s.VisitStartDate.Equals(add7day)).ToList();
                List<OA2021_DelegationInfo> listAdd2day = list_source.Where(s => s.VisitEndDate.Equals(add2day)).ToList();

                if (listAdd7day.Count > 0)
                {
                    string teamNames = "";
                    listAdd7day.ForEach(s => teamNames += s.TeamName + "、");
                    teamNames = teamNames.TrimEnd('、');
                    //发送短信
                    string add7dayZH = dtNow.AddDays(7).ToString("yyyy年MM月dd日");
                    string templateParam = JsonConvert.SerializeObject(new { teams = teamNames, date = add7dayZH });

                    foreach (string postPhoneNumber in list_PhoneNumbers)
                    {
                        string postResult = AliMessagePost.PostMessage(postPhoneNumber, "泛美国际团组", "SMS_461505530", templateParam);
                        Bus_MsgPostInfo _entity = new Bus_MsgPostInfo();
                        _entity.Source = "ALiYun";
                        _entity.TeamNames = teamNames;
                        _entity.PostType = "Dele2";
                        _entity.PhoneNumber = postPhoneNumber;
                        _entity.PostResult = postResult;
                        _grpDeleRep._sqlSugar.Insertable<Bus_MsgPostInfo>(_entity);
                    }
                }

                if (listAdd2day.Count > 0)
                {
                    string teamNames = "";
                    listAdd2day.ForEach(s => teamNames += s.TeamName + "、");
                    teamNames = teamNames.TrimEnd('、');
                    //发送短信
                    string add2dayZH = dtNow.AddDays(2).ToString("yyyy年MM月dd日");
                    string templateParam = JsonConvert.SerializeObject(new { teams = teamNames, date = add2dayZH });
                    foreach (string postPhoneNumber in list_PhoneNumbers)
                    {
                        string postResult = AliMessagePost.PostMessage(postPhoneNumber, "泛美国际团组", "SMS_461575447", templateParam);
                        Bus_MsgPostInfo _entity = new Bus_MsgPostInfo();
                        _entity.Source = "ALiYun";
                        _entity.TeamNames = teamNames;
                        _entity.PostType = "Dele1";
                        _entity.PhoneNumber = postPhoneNumber;
                        _entity.PostResult = postResult;
                        _grpDeleRep._sqlSugar.Insertable<Bus_MsgPostInfo>(_entity);
                    }
                }
            }
        }

        /// <summary>
        /// 企业微信发送消息
        /// </summary>
        public static async void PostMessageByWebhook()
        {
            DateTime dtNow = DateTime.Now;
            string now = dtNow.ToString("yyyy-MM-dd");
            string add3day = dtNow.AddDays(2).ToString("yyyy-MM-dd"); //结束出访前3天(含今天)
            string add7day = dtNow.AddDays(6).ToString("yyyy-MM-dd"); //开始出访7天内(含今天)
            string minus1day = dtNow.AddDays(-1).ToString("yyyy-MM-dd"); //于昨日结束

            //string sql = string.Format(@" Select * From Grp_DelegationInfo With(Nolock) Where IsDel=0 And VisitEndDate ='{0}' Or VisitStartDate='{1}' ", add3day, add7day);
            //List<Grp_DelegationInfo> list_source = _grpDeleRep._sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToList();



            string sql7day = string.Format(@" Select * From Grp_DelegationInfo With(Nolock) where IsDel = 0 And VisitStartDate Between '{0} 00:00:00' And  '{1} 23:59:59' Order By VisitStartDate Asc ", now, add7day);
            string sql3day = string.Format(@" Select * From Grp_DelegationInfo With(Nolock) where IsDel = 0 And VisitEndDate Between '{0} 00:00:00' And  '{1} 23:59:59' Order By VisitEndDate Asc ", now, add3day);
            string sqlm1day = string.Format(@" Select * From Grp_DelegationInfo With(Nolock) where IsDel = 0 And VisitEndDate Between '{0} 00:00:00' And  '{1} 23:59:59' Order By VisitEndDate Asc ", minus1day, minus1day);


            List<Grp_DelegationInfo> listAdd7day = _grpDeleRep._sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql7day).ToList();
            List<Grp_DelegationInfo> listAdd3day = _grpDeleRep._sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql3day).ToList();
            List<Grp_DelegationInfo> listMinus1day = _grpDeleRep._sqlSugar.SqlQueryable<Grp_DelegationInfo>(sqlm1day).ToList();

            await AppNoticeLibrary.SendChatMsg_GroupRemindersToCaiwu(listAdd7day, listAdd3day, listMinus1day, QiyeWeChatEnum.CaiWuChat02);
            await AppNoticeLibrary.SendChatMsg_GroupRemindersToGuojiao(listAdd3day, QiyeWeChatEnum.GuoJiaoChat01);

        }

        public static async void PostMessageByWebhook_VisitToHR()
        {
            DateTime dtNow = DateTime.Now;
            if (dtNow.DayOfWeek == DayOfWeek.Friday)
            {
                string add1day = dtNow.AddDays(1).ToString("yyyy-MM-dd");
                string add7day = dtNow.AddDays(7).ToString("yyyy-MM-dd");

                //string sql = string.Format(@" Select * From Grp_DelegationInfo With(Nolock) Where IsDel=0 And VisitEndDate ='{0}' Or VisitStartDate='{1}' ", add3day, add7day);
                //List<Grp_DelegationInfo> list_source = _grpDeleRep._sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToList();

                string sql7day = string.Format(@" Select * From Grp_DelegationInfo With(Nolock) where IsDel = 0 And VisitStartDate Between '{0} 00:00:00' And  '{1} 23:59:59' Order By VisitStartDate Asc ", add1day, add7day);

                List<Grp_DelegationInfo> listAdd7day = _grpDeleRep._sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql7day).ToList();

                List<string> temp = new List<string>() { "234", "309" };
                //List<string> temp = new List<string>() { "234" };
                await AppNoticeLibrary.SendUserMsg_DelegationVisit_ToHR(listAdd7day, temp);
            }
        }

        public static async void PostMessageByWebhook_CRMStatistics()
        {
            DateTime dtNow = DateTime.Now;
            if (dtNow.DayOfWeek == DayOfWeek.Monday)
            {

                string dt_1day = dtNow.AddDays(-1).ToString("yyyy-MM-dd");
                string dt_7day = dtNow.AddDays(-7).ToString("yyyy-MM-dd");

                string sql_users = string.Format(@" Select * From Sys_Users with(Nolock) where IsDel = 0 And DepId = 6 And Id Not In (321) ");
                List<Sys_Users> userList = _grpDeleRep._sqlSugar.SqlQueryable<Sys_Users>(sql_users).ToList();

                List<CRMWeekStatisticsView> source = new List<CRMWeekStatisticsView>();
                int total_insert = 0;
                int total_delete = 0;

                foreach (var u in userList)
                {
                    string sql_temp1 = string.Format(@" Select * From Crm_NewClientData With(Nolock) where CreateUserId = {0} And CreateTime Between '{1} 00:00:00' And '{2} 23:59:59' ", u.Id, dt_7day, dt_1day);
                    List<Crm_NewClientData> crmList = _grpDeleRep._sqlSugar.SqlQueryable<Crm_NewClientData>(sql_temp1).ToList();

                    int iNum = crmList.Where(s => s.IsDel == 0).Count();
                    int dNum = crmList.Where(s => s.IsDel == 1).Count();
                    string userName = u.CnName;

                    total_insert += iNum;
                    total_delete += dNum;

                    CRMWeekStatisticsView sourceItem = new CRMWeekStatisticsView()
                    {
                        DeleteNum = dNum,
                        InsertNum = iNum,
                        UserName = userName
                    };

                    source.Add(sourceItem);
                }
                List<string> temp = new List<string>() { "234", "309" };
                await AppNoticeLibrary.SendUserMsg_CRMStatistics_ToHR(source, temp, dt_7day, dt_1day);
            }

            if (dtNow.Day == 1)
            {
                string dt_last = dtNow.AddDays(-1).ToString("yyyy-MM-dd");
                string dt_first = dtNow.AddDays(-1).ToString("yyyy-MM-01");

                string sql_users = string.Format(@" Select * From Sys_Users with(Nolock) where IsDel = 0 And DepId = 6 And Id Not In (321) ");
                List<Sys_Users> userList = _grpDeleRep._sqlSugar.SqlQueryable<Sys_Users>(sql_users).ToList();

                List<CRMWeekStatisticsView> source = new List<CRMWeekStatisticsView>();
                int total_insert = 0;
                int total_delete = 0;

                foreach (var u in userList)
                {
                    string sql_temp1 = string.Format(@" Select * From Crm_NewClientData With(Nolock) where CreateUserId = {0} And CreateTime Between '{1} 00:00:00' And '{2} 23:59:59' ", u.Id, dt_first, dt_last);
                    List<Crm_NewClientData> crmList = _grpDeleRep._sqlSugar.SqlQueryable<Crm_NewClientData>(sql_temp1).ToList();

                    int iNum = crmList.Where(s => s.IsDel == 0).Count();
                    int dNum = crmList.Where(s => s.IsDel == 1).Count();
                    string userName = u.CnName;

                    total_insert += iNum;
                    total_delete += dNum;

                    CRMWeekStatisticsView sourceItem = new CRMWeekStatisticsView()
                    {
                        DeleteNum = dNum,
                        InsertNum = iNum,
                        UserName = userName
                    };

                    source.Add(sourceItem);
                }
                List<string> temp = new List<string>() { "234", "309" };
                await AppNoticeLibrary.SendUserMsg_CRMStatistics_Month_ToHR(source, temp, dt_first, dt_last, total_insert, total_delete);
            }

        }
    }
}