using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Edu.Common.Enum;
using Edu.Model.Entity.System;
using Edu.Model.ViewModel.System;
using Edu.Repository.System;
using VT.FW.DB;
using Aliyun.Net.SDK.Core;

namespace Edu.Module.System
{
    public class MsgLogModule
    {
        /// <summary>
        /// 短信记录仓储层对象
        /// </summary>
        private readonly RB_Msg_LogRepository msgLogRepository = new RB_Msg_LogRepository();

        /// <summary>
        /// 短信配置仓储层对象
        /// </summary>
        private readonly RB_Msg_BaseRepository msgBaseRepository = new RB_Msg_BaseRepository();

        /// <summary>
        /// 短信模板配置仓储层对象
        /// </summary>
        private readonly RB_Msg_BaseTemplateRepository msgBaseTemplateRepository = new RB_Msg_BaseTemplateRepository();


        /// <summary>
        /// 系统消息记录仓储层对象
        /// </summary>
        private readonly RB_System_LogRepository systemLogRepository = new RB_System_LogRepository();

        #region  短信记录
        /// <summary>
        /// 获取发送短信记录信息
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Msg_Log_ViewModel> GetPageListRepository(int pageIndex, int pageSize, out long rowsCount, Model.ViewModel.System.RB_Msg_Log_ViewModel query)
        {
            return msgLogRepository.GetPageListRepository(pageIndex, pageSize, out rowsCount, query);
        }
        #endregion

        #region 短信配置





        /// <summary>
        /// 获取短信配置列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Msg_Base_Function_ViewModel> GetMsgBaseListModule(RB_Msg_Base_Function_ViewModel query)
        {
            return msgBaseRepository.GetListRepository(query);
        }

        /// <summary>
        /// 获取短信配置列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Msg_Base_Function_ViewModel> GetMsgBasePageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Msg_Base_Function_ViewModel query)
        {
            return msgBaseRepository.GetPageListRepository(pageIndex, pageSize, out rowsCount, query);
        }
        /// <summary>
        /// 新增修改 短信配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetMsgBaseModule(RB_Msg_Base model)
        {
            if (model.ID > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Msg_Base.CreateDate),model.CreateDate},
                    { nameof(RB_Msg_Base.CreateBy),model.CreateBy},
                    { nameof(RB_Msg_Base.StoreType),model.StoreType},
                      { nameof(RB_Msg_Base.MsgConfigure),model.MsgConfigure}
                };
                return msgBaseRepository.Update(fileds, new WhereHelper(nameof(RB_Msg_Base.ID), model.ID));
            }
            else
            {
                var newId = msgBaseRepository.Insert(model);
                return newId > 0;
            }
        }

        /// <summary>
        /// 根据短信配置编号获取短信配置详细信息
        /// </summary>
        /// <param name="ClassId"></param>
        /// <returns></returns>
        public RB_Msg_Base_Function_ViewModel GetMsgBaseModule(object ClassId)
        {
            return msgBaseRepository.GetEntity<RB_Msg_Base_Function_ViewModel>(ClassId);
        }

        /// <summary>
        /// 删除短信配置
        /// </summary>
        /// <param name="ClassId"></param>
        /// <returns></returns>
        public bool RemoveMsgBaseModule(object ID)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Msg_Base.Status),(int)DateStateEnum.Delete},
            };
            return msgBaseRepository.Update(fileds, new WhereHelper(nameof(RB_Msg_Base.ID), ID));
        }
        #endregion

        #region 短信模板配置
        /// <summary>
        /// 获取短信模板配置列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Msg_BaseTemplate_ViewModel> GetMsgBaseTemplateListModule(RB_Msg_BaseTemplate_ViewModel query)
        {
            return msgBaseTemplateRepository.GetListRepository(query);
        }

        /// <summary>
        /// 获取短信模板配置分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Msg_BaseTemplate_ViewModel> GetMsgBaseTemplatePageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Msg_BaseTemplate_ViewModel query)
        {
            return msgBaseTemplateRepository.GetPageListRepository(pageIndex, pageSize, out rowsCount, query);
        }
        /// <summary>
        /// 新增修改 短信模板配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetMsgBaseTemplateModule(RB_Msg_BaseTemplate_ViewModel model)
        {
            if (model.ID > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Msg_BaseTemplate_ViewModel.CreateDate),model.CreateDate},
                    { nameof(RB_Msg_BaseTemplate_ViewModel.CreateBy),model.CreateBy},
                    { nameof(RB_Msg_BaseTemplate_ViewModel.TemplateStaus),model.TemplateStaus},
                    { nameof(RB_Msg_BaseTemplate_ViewModel.TemplateId),model.TemplateId},
                    { nameof(RB_Msg_BaseTemplate_ViewModel.StoreType),model.StoreType},
                     { nameof(RB_Msg_BaseTemplate_ViewModel.Sign),model.Sign},
                    { nameof(RB_Msg_BaseTemplate_ViewModel.BaseTemplateType),model.BaseTemplateType}
                };
                return msgBaseTemplateRepository.Update(fileds, new WhereHelper(nameof(RB_Msg_BaseTemplate_ViewModel.ID), model.ID));
            }
            else
            {
                var newId = msgBaseTemplateRepository.Insert(model);
                return newId > 0;
            }
        }

        /// <summary>
        /// 根据短信模板配置编号获取短信配置详细信息
        /// </summary>
        /// <param name="ClassId"></param>
        /// <returns></returns>
        public RB_Msg_BaseTemplate_ViewModel GetMsgBaseTemplateModule(object ClassId)
        {
            return msgBaseTemplateRepository.GetEntity<RB_Msg_BaseTemplate_ViewModel>(ClassId);
        }

        /// <summary>
        /// 删除短信模板配置
        /// </summary>
        /// <param name="ClassId"></param>
        /// <returns></returns>
        public bool RemoveMsgBaseTemplateModule(object ID)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Msg_BaseTemplate_ViewModel.TemplateStaus),(int)DateStateEnum.Delete},
            };
            return msgBaseTemplateRepository.Update(fileds, new WhereHelper(nameof(RB_Msg_BaseTemplate_ViewModel.ID), ID));
        }
        #endregion

        #region 发送短信统一方法
        public void SendMsg(object PhoneMessage, Common.Enum.System.BaseTemplateTypeEnum BaseTemplateType, RB_Msg_Log msgLogModel)
        {
            //查询当前集团的短信基础配置
            var msgBaseList = msgBaseRepository.GetListRepository(new RB_Msg_Base_Function_ViewModel { Group_Id = msgLogModel.Group_Id });
            //查询当前下面是否有模板
            var allMsgBaseTemplateList = msgBaseTemplateRepository.GetListRepository(new RB_Msg_BaseTemplate_ViewModel { BaseTemplateType = BaseTemplateType, Group_Id = msgLogModel.Group_Id }).Where(x => x.TemplateStaus == 0);
            if (msgBaseList != null && msgBaseList.Any() && allMsgBaseTemplateList != null && allMsgBaseTemplateList.Any())
            {
                RB_Msg_Base_Function_ViewModel model = new RB_Msg_Base_Function_ViewModel(); // msgBaseList.OrderBy(x => x.ID).FirstOrDefault();
                if (allMsgBaseTemplateList.Where(x => x.BaseTemplateType == BaseTemplateType).GroupBy(x => x.StoreType).Count() > 1)
                {
                    model = msgBaseList.OrderBy(x => x.ID).FirstOrDefault();
                }
                else
                {
                    model = msgBaseList.Where(x => x.StoreType == allMsgBaseTemplateList.FirstOrDefault().StoreType).FirstOrDefault();
                }
                if (model != null && model.ID > 0)
                {
                    if (!string.IsNullOrWhiteSpace(model.MsgConfigure))
                    {
                        msgLogModel.StoreType = model.StoreType;
                        msgLogModel.MsgConfigure = model.MsgConfigure;
                        int id = msgLogRepository.Insert(msgLogModel);
                        model.MsgBase = Common.Plugin.JsonHelper.DeserializeObject<RB_Msg_Base_ViewModel>(model.MsgConfigure);
                        var msgBaseTemplateList = allMsgBaseTemplateList.Where(x => x.BaseTemplateType == BaseTemplateType);
                        if (!string.IsNullOrWhiteSpace(model.MsgBase.AccessKeyId) && !string.IsNullOrWhiteSpace(model.MsgBase.AccessSecret) && !string.IsNullOrWhiteSpace(model.MsgBase.Domain) && !string.IsNullOrWhiteSpace(model.MsgBase.RegionId))
                        {
                            if (msgBaseTemplateList != null && msgBaseTemplateList.Any(x => x.TemplateStaus == 0))
                            {
                                var msgBaseTemplateModel = msgBaseTemplateList.Where(x => x.TemplateStaus == 0).FirstOrDefault();
                                if (Common.Config.IsSendMsg == 1)
                                {
                                    ThirdCore.Message.SMSService.SendMsg(msgLogModel.ReceiverPhone, PhoneMessage, msgBaseTemplateModel.TemplateId, msgBaseTemplateModel.Sign, model.MsgBase.Domain, model.MsgBase.AccessKeyId, model.MsgBase.AccessSecret, model.MsgBase.RegionId, id.ToString());
                                }

                            }
                        }
                    }
                }
            }
            // ThirdCore.Message.SMSService.SendMsg("13551132417", PhoneMessage, "SMS_201722097", "印象之旅", "dysmsapi.aliyuncs.com", "LTAIwE7l9dImZSa3", "j47Ajn0d0WzUCIX8Biyj3P2r8QDltI", "cn-hangzhou");
        }


        /// <summary>
        /// 更新消息发送状态
        /// </summary>
        public void UpdateMsgSendStatus()
        {
            var list = msgLogRepository.GetListRepository(new RB_Msg_Log { SendStatus = Common.Enum.System.MsgSendStatusEnum.InReceipt });
            foreach (var item in list.GroupBy(x => new { x.ReceiverPhone, x.StoreType, x.MsgConfigure, CreateDate = x.CreateDate.ToString("yyyyMMdd") }))
            {
                if (item.Key.StoreType == Common.Enum.Public.StoreTypeEnum.Alicloud)
                {
                    try
                    {
                        RB_Msg_Base_ViewModel msgBase = new RB_Msg_Base_ViewModel();
                        if (!string.IsNullOrWhiteSpace(item.Key.MsgConfigure))
                        {
                            msgBase = Common.Plugin.JsonHelper.DeserializeObject<RB_Msg_Base_ViewModel>(item.Key.MsgConfigure);
                        }
                        Aliyun.Acs.Dysmsapi.Model.V20170525.QuerySendDetailsResponse querySendDetailsResponse = Edu.ThirdCore.Message.MessageCore.QuerySendDetails(item.Key.ReceiverPhone, DateTime.Now.ToString("yyyyMMdd"), "", msgBase.Domain, msgBase.AccessKeyId, msgBase.AccessSecret, msgBase.RegionId);
                        if (querySendDetailsResponse.Code == "OK")
                        {
                            if (querySendDetailsResponse.SmsSendDetailDTOs != null && querySendDetailsResponse.SmsSendDetailDTOs.Any())
                            {
                                foreach (var modelSmsSendDetailDTO in querySendDetailsResponse.SmsSendDetailDTOs)
                                {
                                    int sendStatus = 1;
                                    if (modelSmsSendDetailDTO != null && !string.IsNullOrWhiteSpace(modelSmsSendDetailDTO.OutId))
                                    {
                                        sendStatus = (int)(modelSmsSendDetailDTO.SendStatus ?? 1);
                                    }
                                    if (sendStatus > 1)
                                    {
                                        Dictionary<string, object> fileds = new Dictionary<string, object>()
                                        {
                                            { nameof(RB_Msg_Log.SendStatus),sendStatus}
                                        };
                                        msgLogRepository.Update(fileds, new WhereHelper(nameof(RB_Msg_Log.ID), Convert.ToInt32(modelSmsSendDetailDTO.OutId)));
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Common.Plugin.LogHelper.Write(ex, "UpdateMsgSendStatus");
                    }
                }
            }
        }


        public bool SendCode(string code, Common.Enum.System.BaseTemplateTypeEnum BaseTemplateType, RB_Msg_Log msgLogModel)
        {
            bool flag = false;
            //查询当前集团的短信基础配置
            var msgBaseList = msgBaseRepository.GetListRepository(new RB_Msg_Base_Function_ViewModel { Group_Id = msgLogModel.Group_Id });
            //查询当前下面是否有模板
            var allMsgBaseTemplateList = msgBaseTemplateRepository.GetListRepository(new RB_Msg_BaseTemplate_ViewModel { BaseTemplateType = BaseTemplateType, Group_Id = msgLogModel.Group_Id }).Where(x => x.TemplateStaus == 0);
            if (msgBaseList != null && msgBaseList.Any() && allMsgBaseTemplateList != null && allMsgBaseTemplateList.Any())
            {
                RB_Msg_Base_Function_ViewModel model = new RB_Msg_Base_Function_ViewModel(); // msgBaseList.OrderBy(x => x.ID).FirstOrDefault();
                if (allMsgBaseTemplateList.Where(x => x.BaseTemplateType == BaseTemplateType).GroupBy(x => x.StoreType).Count() > 1)
                {
                    model = msgBaseList.OrderBy(x => x.ID).FirstOrDefault();
                }
                else
                {
                    model = msgBaseList.Where(x => x.StoreType == allMsgBaseTemplateList.FirstOrDefault().StoreType).FirstOrDefault();
                }
                if (model != null && model.ID > 0)
                {
                    if (!string.IsNullOrWhiteSpace(model.MsgConfigure))
                    {
                        msgLogModel.StoreType = model.StoreType;
                        msgLogModel.MsgConfigure = model.MsgConfigure;
                        int id = msgLogRepository.Insert(msgLogModel);
                        model.MsgBase = Common.Plugin.JsonHelper.DeserializeObject<RB_Msg_Base_ViewModel>(model.MsgConfigure);
                        var msgBaseTemplateList = allMsgBaseTemplateList.Where(x => x.BaseTemplateType == BaseTemplateType);
                        if (!string.IsNullOrWhiteSpace(model.MsgBase.AccessKeyId) && !string.IsNullOrWhiteSpace(model.MsgBase.AccessSecret) && !string.IsNullOrWhiteSpace(model.MsgBase.Domain) && !string.IsNullOrWhiteSpace(model.MsgBase.RegionId))
                        {
                            if (msgBaseTemplateList != null && msgBaseTemplateList.Any(x => x.TemplateStaus == 0))
                            {
                                var msgBaseTemplateModel = msgBaseTemplateList.Where(x => x.TemplateStaus == 0).FirstOrDefault();
                                if (Common.Config.IsSendMsg == 1)
                                {
                                    ThirdCore.Message.SMSService.SendCode(msgLogModel.ReceiverPhone, code, msgBaseTemplateModel.TemplateId, msgBaseTemplateModel.Sign, model.MsgBase.Domain, model.MsgBase.AccessKeyId, model.MsgBase.AccessSecret, model.MsgBase.RegionId, id.ToString());
                                    flag = true;
                                }

                            }
                        }
                    }
                }
            }
            return flag;

        }
        #endregion


        #region 系统消息
        /// <summary>
        /// 获取发送系统消息记录信息
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_System_Log_ViewModel> GetSystemLogListRepository(RB_System_Log_ViewModel query)
        {
            return systemLogRepository.GetListRepository(query);
        }

        /// <summary>
        /// 获取发送系统消息记录信息
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_System_Log_ViewModel> GetSystemLogPageListRepository(int pageIndex, int pageSize, out long rowsCount, RB_System_Log_ViewModel query)
        {
            return systemLogRepository.GetPageListRepository(pageIndex, pageSize, out rowsCount, query);
        }
        #endregion
    }
}
