using NPOI.SS.Formula.Functions;
using OASystem.Domain.Entities.Financial;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.ViewModels.Groups;
using OASystem.Domain.ViewModels.QiYeWeChat;
using OASystem.Infrastructure.Repositories.Groups;

namespace OASystem.API.OAMethodLib.QiYeWeChatAPI.AppNotice
{
    public static class AppNoticeLibrary
    {
        private static readonly IQiYeWeChatApiService _qiYeWeChatApiService = AutofacIocManager.Instance.GetService<IQiYeWeChatApiService>();

        private static readonly DelegationInfoRepository _grpDeleRep = AutofacIocManager.Instance.GetService<DelegationInfoRepository>();

        #region 获取企微Id

        public static List<string> GetQiyeChatUserIdList(List<string> userId)
        {
            List<string> result = new List<string>();

            try
            {
                foreach (string item in userId)
                {
                    int uid = int.Parse(item);
                    Sys_Users users = _grpDeleRep.Query<Sys_Users>(s => s.Id == uid).First();
                    if (!string.IsNullOrEmpty(users.QiyeChatUserId))
                    {
                        result.Add(users.QiyeChatUserId);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return result;
        }

        #endregion

        #region 确认出团

        /// <summary>
        /// 向指定群聊发送- 确认出团 -通知
        /// </summary>
        /// <param name="diId"></param>
        /// <param name="qwEnum"></param>
        /// <returns></returns>
        public static async Task<bool> SendChatMsg_GroupStatus_Create(int diId, QiyeWeChatEnum qwEnum)
        {
            Grp_DelegationInfo entity = _grpDeleRep.Query<Grp_DelegationInfo>(s => s.Id == diId).First();

            string dateRange = string.Format(@"{0}至{1}", entity.VisitStartDate.ToString("yyyy-MM-dd"), entity.VisitEndDate.ToString("yyyy-MM-dd"));

            string grpTypeStr = (_grpDeleRep.Query<Sys_SetData>(s => s.Id == entity.TeamDid).First()).Name;

            GroupStatus_CreateModel info = new GroupStatus_CreateModel()
            {
                ClientName = entity.ClientName,
                ClientUnit = entity.ClientUnit,
                TeamName = entity.TeamName,
                VisitDays = entity.VisitDays,
                VisitPNumber = entity.VisitPNumber,
                VisitDateRange = dateRange,
                TeamDid_Text = grpTypeStr
            };
            string chatId = qwEnum.GetEnumDescription();
            //发送信息
            ResponseBase result = await _qiYeWeChatApiService.GroupStatus_SendChatMsg_Markdown(chatId, MarkdownLib.GroupStatus_Create(info));
            if (result.errcode != 0)
            {
                //抄送日志 
                return false;
            }

            return true;
        }

        /// <summary>
        /// 向指定用户发送- 确认出团 -通知
        /// </summary>
        /// <param name="diId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static async Task<bool> SendUserMsg_GroupStatus_Create(int diId, List<string> userId)
        {
            Grp_DelegationInfo entity = _grpDeleRep.Query<Grp_DelegationInfo>(s => s.Id == diId).First();

            string dateRange = string.Format(@"{0}至{1}", entity.VisitStartDate.ToString("yyyy-MM-dd"), entity.VisitEndDate.ToString("yyyy-MM-dd"));

            string grpTypeStr = (_grpDeleRep.Query<Sys_SetData>(s => s.Id == entity.TeamDid).First()).Name;

            GroupStatus_CreateModel info = new GroupStatus_CreateModel()
            {
                ClientName = entity.ClientName,
                ClientUnit = entity.ClientUnit,
                TeamName = entity.TeamName,
                VisitDays = entity.VisitDays,
                VisitPNumber = entity.VisitPNumber,
                VisitDateRange = dateRange,
                TeamDid_Text = grpTypeStr
            };

            //发送信息
            List<string> qwUserIdList = GetQiyeChatUserIdList(userId);
            if (qwUserIdList.Count > 0)
            {
                ResponseBase result = await _qiYeWeChatApiService.GroupStatus_SendMessage_ToUser_Markdown(qwUserIdList, MarkdownLib.GroupStatus_Create(info));

                if (result.errcode != 0)
                {
                    //抄送日志 
                    return false;
                }
            }
            return true;
        }

        #endregion

        #region 团组费用审核


        /// <summary>
        /// 向指定群聊发送- 费用申请 -通知
        /// </summary>
        /// <param name="diId"></param>
        /// <param name="qwEnum"></param>
        /// <returns></returns>
        public static async Task<bool> SendChatMsg_GroupStatus_ApplyFee(int Grp_CreditCardPaymentId, int sign, QiyeWeChatEnum qwEnum)
        {
            string chatId = qwEnum.GetEnumDescription();

            Grp_CreditCardPayment ccp = _grpDeleRep.Query<Grp_CreditCardPayment>(s => s.Id == Grp_CreditCardPaymentId).First();
            Grp_DelegationInfo group = _grpDeleRep.Query<Grp_DelegationInfo>(s => s.Id == ccp.DIId).First();

            Sys_SetData payMoneyCurrencySetData = _grpDeleRep.Query<Sys_SetData>(s => s.Id == ccp.PaymentCurrency).First();
            string priceStr = string.Format(@"{0} {1}", ccp.PayMoney, payMoneyCurrencySetData.Name);

            List<Grp_CreditCardPayment> entityList = _grpDeleRep
                   .Query<Grp_CreditCardPayment>(s => s.DIId == ccp.DIId && s.IsDel == 0 && s.CreateUserId > 0 && s.IsAuditGM == 0)
                   .ToList();

            GroupStatus_ApplyFeeModel info = new GroupStatus_ApplyFeeModel()
            {
                QueueCount = entityList.Count,
                TeamName = group.TeamName,
                Price = priceStr
            };

            if (sign == 2)
            {
                info.TitleStr = "[更新]一项费用待审核";
            }

            //CTable
            #region CTable

            if (ccp.CTable == 76)//76,酒店预订
            {
                Grp_HotelReservations _HotelReservations = _grpDeleRep.Query<Grp_HotelReservations>(s => s.Id == ccp.CId).First();
                info.CreateDt = _HotelReservations.CreateTime.ToString("yyyy-MM-dd HH:mm");

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _HotelReservations.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "酒店预订";
                info.PriceName = _HotelReservations.HotelName;
            }
            else if (ccp.CTable == 79) //79://车/导游地接
            {
                Grp_CarTouristGuideGroundReservations _CarTouristGuideGroundReservations = _grpDeleRep.Query<Grp_CarTouristGuideGroundReservations>(s => s.Id == ccp.CId).First();
                info.CreateDt = _CarTouristGuideGroundReservations.CreateTime.ToString("yyyy-MM-dd HH:mm");

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _CarTouristGuideGroundReservations.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "车/导游地接";
                info.PriceName = _CarTouristGuideGroundReservations.PriceName;
            }
            else if (ccp.CTable == 80) //签证
            {
                List<SimplClientInfo> clientNameList = getSimplClientList(group.Id);
                Grp_VisaInfo _VisaInfos = _grpDeleRep.Query<Grp_VisaInfo>(s => s.Id == ccp.CId).First();
                info.CreateDt = _VisaInfos.CreateTime.ToString("yyyy-MM-dd HH:mm");

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _VisaInfos.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "签证";
                info.PriceName = getClientNameStr(clientNameList, _VisaInfos.VisaClient);
            }
            else if (ccp.CTable == 81)//邀请/公务活动
            {
                Grp_InvitationOfficialActivities _InvitationOfficialActivities = _grpDeleRep.Query<Grp_InvitationOfficialActivities>(s => s.Id == ccp.CId).First();
                info.CreateDt = _InvitationOfficialActivities.CreateTime.ToString("yyyy-MM-dd HH:mm");

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _InvitationOfficialActivities.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "邀请/公务活动";
                info.PriceName = _InvitationOfficialActivities.InviterArea;
            }
            else if (ccp.CTable == 82)//团组客户保险
            {
                List<SimplClientInfo> clientNameList = getSimplClientList(group.Id);
                Grp_Customers _Customers = _grpDeleRep.Query<Grp_Customers>(s => s.Id == ccp.CId).First();
                info.CreateDt = _Customers.CreateTime.ToString("yyyy-MM-dd HH:mm");

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _Customers.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "团组客户保险";
                info.PriceName = getClientNameStr(clientNameList, _Customers.ClientName);
            }
            else if (ccp.CTable == 85) //机票预订
            {
                Grp_AirTicketReservations _AirTicketReservations = _grpDeleRep.Query<Grp_AirTicketReservations>(s => s.Id == ccp.CId).First();
                info.CreateDt = _AirTicketReservations.CreateTime.ToString("yyyy-MM-dd HH:mm");

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _AirTicketReservations.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "机票预订";
                info.PriceName = "(" + _AirTicketReservations.FlightsCode + ")";
            }
            else if (ccp.CTable == 98) //其他款项
            {
                Grp_DecreasePayments _DecreasePayments = _grpDeleRep.Query<Grp_DecreasePayments>(s => s.Id == ccp.CId).First();
                info.CreateDt = _DecreasePayments.CreateTime.ToString("yyyy-MM-dd HH:mm");

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _DecreasePayments.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "其他款项";
                info.PriceName = _DecreasePayments.PriceName;
            }
            #endregion


            //发送信息
            ResponseBase result = await _qiYeWeChatApiService.GroupStatus_SendChatMsg_Markdown(chatId, MarkdownLib.GroupStatus_ApplyFee(info));
            if (result.errcode != 0)
            {
                //抄送日志 
                return false;
            }

            return true;
        }

        /// <summary>
        /// 向财务群发送费用审核结果通知(审核通过条件下发送)
        /// </summary>
        /// <param name="Grp_CreditCardPaymentId"></param>
        /// <param name="qwEnum"></param>
        /// <returns></returns>
        public static async Task<bool> SendChatMsg_GroupStatus_AuditFee(int Grp_CreditCardPaymentId, QiyeWeChatEnum qwEnum)
        {

            string chatId = qwEnum.GetEnumDescription();

            Grp_CreditCardPayment ccp = _grpDeleRep.Query<Grp_CreditCardPayment>(s => s.Id == Grp_CreditCardPaymentId).First();
            Grp_DelegationInfo group = _grpDeleRep.Query<Grp_DelegationInfo>(s => s.Id == ccp.DIId).First();

            Sys_SetData payMoneyCurrencySetData = _grpDeleRep.Query<Sys_SetData>(s => s.Id == ccp.PaymentCurrency).First();
            string priceStr = string.Format(@"{0} {1}", ccp.PayMoney, payMoneyCurrencySetData.Name);

            AuditResult_ApplyFee_GroupModel info = new AuditResult_ApplyFee_GroupModel()
            {
                TeamName = group.TeamName,
                Price = priceStr,
                GMAuditDate = "-"
            };

            DateTime gmAuditDt;
            bool bGMAuditDt = DateTime.TryParse(ccp.AuditGMDate, out gmAuditDt);
            info.GMAuditDate = gmAuditDt.ToString("yyyy-MM-dd HH:mm");

            //CTable
            #region CTable

            if (ccp.CTable == 76)//76,酒店预订
            {
                Grp_HotelReservations _HotelReservations = _grpDeleRep.Query<Grp_HotelReservations>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _HotelReservations.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "酒店预订";
                info.PriceName = _HotelReservations.HotelName;
            }
            else if (ccp.CTable == 79) //79://车/导游地接
            {
                Grp_CarTouristGuideGroundReservations _CarTouristGuideGroundReservations = _grpDeleRep.Query<Grp_CarTouristGuideGroundReservations>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _CarTouristGuideGroundReservations.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "车/导游地接";
                info.PriceName = _CarTouristGuideGroundReservations.PriceName;
            }
            else if (ccp.CTable == 80) //签证
            {
                List<SimplClientInfo> clientNameList = getSimplClientList(group.Id);
                Grp_VisaInfo _VisaInfos = _grpDeleRep.Query<Grp_VisaInfo>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _VisaInfos.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "签证";
                info.PriceName = getClientNameStr(clientNameList, _VisaInfos.VisaClient);
            }
            else if (ccp.CTable == 81)//邀请/公务活动
            {
                Grp_InvitationOfficialActivities _InvitationOfficialActivities = _grpDeleRep.Query<Grp_InvitationOfficialActivities>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _InvitationOfficialActivities.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "邀请/公务活动";
                info.PriceName = _InvitationOfficialActivities.InviterArea;
            }
            else if (ccp.CTable == 82)//团组客户保险
            {
                List<SimplClientInfo> clientNameList = getSimplClientList(group.Id);
                Grp_Customers _Customers = _grpDeleRep.Query<Grp_Customers>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _Customers.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "团组客户保险";
                info.PriceName = getClientNameStr(clientNameList, _Customers.ClientName);
            }
            else if (ccp.CTable == 85) //机票预订
            {
                Grp_AirTicketReservations _AirTicketReservations = _grpDeleRep.Query<Grp_AirTicketReservations>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _AirTicketReservations.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "机票预订";
                info.PriceName = "(" + _AirTicketReservations.FlightsCode + ")";
            }
            else if (ccp.CTable == 98) //其他款项
            {
                Grp_DecreasePayments _DecreasePayments = _grpDeleRep.Query<Grp_DecreasePayments>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _DecreasePayments.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "其他款项";
                info.PriceName = _DecreasePayments.PriceName;
            }
            #endregion

            //发送信息
            ResponseBase result = await _qiYeWeChatApiService.GroupStatus_SendChatMsg_Markdown(chatId, MarkdownLib.AuditResult_ApplyFee_Chat(info));
            if (result.errcode != 0)
            {
                //抄送日志 
                return false;
            }

            return true;
        }


        /// <summary>
        /// 向指定用户发送-团组费用审核结果
        /// </summary>
        /// <param name="Grp_CreditCardPaymentId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static async Task<bool> SendUserMsg_GroupStatus_AuditFee(int Grp_CreditCardPaymentId, List<string> userId, QiyeWeChatEnum qwEnum)
        {
            Grp_CreditCardPayment ccp = _grpDeleRep.Query<Grp_CreditCardPayment>(s => s.Id == Grp_CreditCardPaymentId).First();
            Grp_DelegationInfo group = _grpDeleRep.Query<Grp_DelegationInfo>(s => s.Id == ccp.DIId).First();

            Sys_SetData payMoneyCurrencySetData = _grpDeleRep.Query<Sys_SetData>(s => s.Id == ccp.PaymentCurrency).First();
            string priceStr = string.Format(@"{0} {1}", ccp.PayMoney, payMoneyCurrencySetData.Name);

            AuditResult_ApplyFee_GroupModel info = new AuditResult_ApplyFee_GroupModel()
            {
                TeamName = group.TeamName,
                Price = priceStr,
                GMAuditDate = "-"
            };

            DateTime gmAuditDt;
            bool bGMAuditDt = DateTime.TryParse(ccp.AuditGMDate, out gmAuditDt);
            info.GMAuditDate = gmAuditDt.ToString("yyyy-MM-dd HH:mm");

            if (ccp.IsAuditGM == 2)
            {
                info.Result = "总经理审核未通过";
                info.ResultColor = "warning";
            }

            //CTable
            #region CTable

            if (ccp.CTable == 76)//76,酒店预订
            {
                Grp_HotelReservations _HotelReservations = _grpDeleRep.Query<Grp_HotelReservations>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _HotelReservations.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "酒店预订";
                info.PriceName = _HotelReservations.HotelName;
            }
            else if (ccp.CTable == 79) //79://车/导游地接
            {
                Grp_CarTouristGuideGroundReservations _CarTouristGuideGroundReservations = _grpDeleRep.Query<Grp_CarTouristGuideGroundReservations>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _CarTouristGuideGroundReservations.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "车/导游地接";
                info.PriceName = _CarTouristGuideGroundReservations.PriceName;
            }
            else if (ccp.CTable == 80) //签证
            {
                List<SimplClientInfo> clientNameList = getSimplClientList(group.Id);
                Grp_VisaInfo _VisaInfos = _grpDeleRep.Query<Grp_VisaInfo>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _VisaInfos.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "签证";
                info.PriceName = getClientNameStr(clientNameList, _VisaInfos.VisaClient);
            }
            else if (ccp.CTable == 81)//邀请/公务活动
            {
                Grp_InvitationOfficialActivities _InvitationOfficialActivities = _grpDeleRep.Query<Grp_InvitationOfficialActivities>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _InvitationOfficialActivities.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "邀请/公务活动";
                info.PriceName = _InvitationOfficialActivities.InviterArea;
            }
            else if (ccp.CTable == 82)//团组客户保险
            {
                List<SimplClientInfo> clientNameList = getSimplClientList(group.Id);
                Grp_Customers _Customers = _grpDeleRep.Query<Grp_Customers>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _Customers.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "团组客户保险";
                info.PriceName = getClientNameStr(clientNameList, _Customers.ClientName);
            }
            else if (ccp.CTable == 85) //机票预订
            {
                Grp_AirTicketReservations _AirTicketReservations = _grpDeleRep.Query<Grp_AirTicketReservations>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _AirTicketReservations.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "机票预订";
                info.PriceName = "(" + _AirTicketReservations.FlightsCode + ")";
            }
            else if (ccp.CTable == 98) //其他款项
            {
                Grp_DecreasePayments _DecreasePayments = _grpDeleRep.Query<Grp_DecreasePayments>(s => s.Id == ccp.CId).First();

                Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == _DecreasePayments.CreateUserId).First();
                Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
                info.CreateUser = string.Format(@"{0}-{1}", job.JobName, user.CnName);

                info.PriceModule = "其他款项";
                info.PriceName = _DecreasePayments.PriceName;
            }
            #endregion

            //发送信息
            List<string> qwUserIdList = GetQiyeChatUserIdList(userId);
            if (qwUserIdList.Count > 0)
            {
                ResponseBase result = await _qiYeWeChatApiService.GroupStatus_SendMessage_ToUser_Markdown(qwUserIdList, MarkdownLib.AuditResult_ApplyFee_User(info));

                if (ccp.IsAuditGM == 1)
                {
                    await SendChatMsg_GroupStatus_AuditFee(Grp_CreditCardPaymentId, qwEnum);
                }
                if (result.errcode != 0)
                {
                    //抄送日志 
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 向指定用户发送-团组费用支付结果
        /// </summary>
        /// <param name="Grp_CreditCardPaymentId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static async Task<bool> SendUserMsg_GroupStatus_PayResult(int Grp_CreditCardPaymentId, List<string> userId)
        {
            Grp_CreditCardPayment ccp = _grpDeleRep.Query<Grp_CreditCardPayment>(s => s.Id == Grp_CreditCardPaymentId).First();
            Grp_DelegationInfo group = _grpDeleRep.Query<Grp_DelegationInfo>(s => s.Id == ccp.DIId).First();

            Sys_SetData payMoneyCurrencySetData = _grpDeleRep.Query<Sys_SetData>(s => s.Id == ccp.PaymentCurrency).First();
            string priceStr = string.Format(@"{0} {1}", ccp.PayMoney, payMoneyCurrencySetData.Name);

            PayResult_Group_ToUserModel info = new PayResult_Group_ToUserModel()
            {
                PayDt = DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
                Price = priceStr,
                TeamName = group.TeamName
            };

            #region CTable

            if (ccp.CTable == 76)//76,酒店预订
            {
                Grp_HotelReservations _HotelReservations = _grpDeleRep.Query<Grp_HotelReservations>(s => s.Id == ccp.CId).First();

                info.PriceModule = "酒店预订";
                info.PriceName = _HotelReservations.HotelName;
            }
            else if (ccp.CTable == 79) //79://车/导游地接
            {
                Grp_CarTouristGuideGroundReservations _CarTouristGuideGroundReservations = _grpDeleRep.Query<Grp_CarTouristGuideGroundReservations>(s => s.Id == ccp.CId).First();

                info.PriceModule = "车/导游地接";
                info.PriceName = _CarTouristGuideGroundReservations.PriceName;
            }
            else if (ccp.CTable == 80) //签证
            {
                List<SimplClientInfo> clientNameList = getSimplClientList(group.Id);
                Grp_VisaInfo _VisaInfos = _grpDeleRep.Query<Grp_VisaInfo>(s => s.Id == ccp.CId).First();

                info.PriceModule = "签证";
                info.PriceName = getClientNameStr(clientNameList, _VisaInfos.VisaClient);
            }
            else if (ccp.CTable == 81)//邀请/公务活动
            {
                Grp_InvitationOfficialActivities _InvitationOfficialActivities = _grpDeleRep.Query<Grp_InvitationOfficialActivities>(s => s.Id == ccp.CId).First();

                info.PriceModule = "邀请/公务活动";
                info.PriceName = _InvitationOfficialActivities.InviterArea;
            }
            else if (ccp.CTable == 82)//团组客户保险
            {
                List<SimplClientInfo> clientNameList = getSimplClientList(group.Id);
                Grp_Customers _Customers = _grpDeleRep.Query<Grp_Customers>(s => s.Id == ccp.CId).First();

                info.PriceModule = "团组客户保险";
                info.PriceName = getClientNameStr(clientNameList, _Customers.ClientName);
            }
            else if (ccp.CTable == 85) //机票预订
            {
                Grp_AirTicketReservations _AirTicketReservations = _grpDeleRep.Query<Grp_AirTicketReservations>(s => s.Id == ccp.CId).First();

                info.PriceModule = "机票预订";
                info.PriceName = "(" + _AirTicketReservations.FlightsCode + ")";
            }
            else if (ccp.CTable == 98) //其他款项
            {
                Grp_DecreasePayments _DecreasePayments = _grpDeleRep.Query<Grp_DecreasePayments>(s => s.Id == ccp.CId).First();

                info.PriceModule = "其他款项";
                info.PriceName = _DecreasePayments.PriceName;
            }
            #endregion

            //发送信息
            List<string> qwUserIdList = GetQiyeChatUserIdList(userId);
            if (qwUserIdList.Count > 0)
            {
                ResponseBase result = await _qiYeWeChatApiService.GroupStatus_SendMessage_ToUser_Markdown(qwUserIdList, MarkdownLib.PayResult_Group_ToUser(info));

                if (result.errcode != 0)
                {
                    //抄送日志 
                    return false;
                }
            }
            return true;
        }

        #endregion

        #region 团组出发、结束提醒（财务群）

        public static async Task<bool> SendChatMsg_GroupRemindersToCaiwu(List<Grp_DelegationInfo> list_7day, List<Grp_DelegationInfo> list_3day, QiyeWeChatEnum qwEnum)
        {
            string chatId = qwEnum.GetEnumDescription();

            ResponseBase result = await _qiYeWeChatApiService.GroupStatus_SendChatMsg_Markdown(chatId, MarkdownLib.GroupRemindersToCaiwuChat(list_7day, list_3day));
            if (result.errcode != 0)
            {
                //抄送日志 
                return false;
            }

            return true;
        }

        #endregion

        #region 日付申请审核

        /// <summary>
        ///  日付申请提交时推送财务群
        /// </summary>
        /// <param name="dailyPayId"></param>
        /// <param name="qwEnum"></param>
        /// <returns></returns>
        public static async Task<bool> DailyPayReminders_Create_ToCaiwuChat(int dailyPayId, int sign, QiyeWeChatEnum qwEnum)
        {
            string chatId = qwEnum.GetEnumDescription();
            Fin_DailyFeePayment fin_DailyFeePayment = _grpDeleRep.Query<Fin_DailyFeePayment>(s => s.Id == dailyPayId).First();

            Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == fin_DailyFeePayment.CreateUserId).First();
            Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
            string users = string.Format(@"{0}-{1}", job.JobName, user.CnName);

            string[] companyArr = new string[] { "未知", "成都泛美商务有限公司", "四川泛美交流有限公司", "成都纽茵教育科技有限公司", "成都鸿企中元科技有限公司", "测试公司1" };
            string companyStr = "未知";
            if (fin_DailyFeePayment.CompanyId < companyArr.Length)
            {
                companyStr = companyArr[fin_DailyFeePayment.CompanyId];
            }

            Sys_SetData sd_tansferType = _grpDeleRep.Query<Sys_SetData>(s => s.Id == fin_DailyFeePayment.TransferTypeId).First();
            Sys_SetData sd_priceType = _grpDeleRep.Query<Sys_SetData>(s => s.Id == fin_DailyFeePayment.PriceTypeId).First();
            string feeSignStr = string.Format(@"{0}-{1}", sd_tansferType.Name, sd_priceType.Name);

            string priceStr = fin_DailyFeePayment.SumPrice.ToString("#0.00");



            DailyPayReminders_Create_ToCaiwuChatModel info = new DailyPayReminders_Create_ToCaiwuChatModel()
            {
                CreateDt = fin_DailyFeePayment.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                CreateUser = users,
                Price = priceStr,
                Company = companyStr,
                FeeSign = feeSignStr,
                PriceName = fin_DailyFeePayment.Instructions

            };

            if (sign == 2)
            {
                info.TitleStr = "[更新]一项费用待审核";
            }

            ResponseBase result = await _qiYeWeChatApiService.GroupStatus_SendChatMsg_Markdown(chatId, MarkdownLib.DailyPayReminders_Create_ToCaiwuChat(info));
            if (result.errcode != 0)
            {
                //抄送日志 
                return false;
            }

            return true;
        }

        /// <summary>
        /// 日付申请审核结果推送给申请人
        /// </summary>
        /// <param name="dailyPayId"></param>
        /// <param name="userId"></param>
        /// <param name="qwEnum"></param>
        /// <returns></returns>
        public static async Task<bool> DailyPayReminder_Audit_ToUser(int dailyPayId, List<string> userId, QiyeWeChatEnum qwEnum)
        {
            Fin_DailyFeePayment fin_DailyFeePayment = _grpDeleRep.Query<Fin_DailyFeePayment>(s => s.Id == dailyPayId).First();

            Sys_Users user = _grpDeleRep.Query<Sys_Users>(s => s.Id == fin_DailyFeePayment.CreateUserId).First();
            Sys_JobPost job = _grpDeleRep.Query<Sys_JobPost>(s => s.Id == user.JobPostId).First();
            string users = string.Format(@"{0}-{1}", job.JobName, user.CnName);

            string priceStr = fin_DailyFeePayment.SumPrice.ToString("#0.00");

            DailyPayReminder_Audit_ToUserModel info = new DailyPayReminder_Audit_ToUserModel()
            {
                Price = priceStr,
                PriceName = fin_DailyFeePayment.Instructions
            };

            if (fin_DailyFeePayment.FAudit == 1)
            {
                info.AuditDate = fin_DailyFeePayment.MAuditDate.ToString("yyyy-MM-dd HH:mm");
                if (fin_DailyFeePayment.MAudit == 1)
                {
                    info.Result = "你有一笔日付申请已通过审核";
                    info.ResultColor = "info";

                    //发送至财务群

                    DailyPayReminder_Audit_ToCaiwuChatModel chatInfo = new DailyPayReminder_Audit_ToCaiwuChatModel()
                    {
                        AuditDate = info.AuditDate,
                        CreateUser = users,
                        Price = priceStr,
                        PriceName = fin_DailyFeePayment.Instructions
                    };

                    string chatId = qwEnum.GetEnumDescription();
                    await _qiYeWeChatApiService.GroupStatus_SendChatMsg_Markdown(chatId, MarkdownLib.DailyPayReminder_Audit_ToCaiwuChat(chatInfo));
                }
                else if (fin_DailyFeePayment.MAudit == 2)
                {
                    info.Result = "你有一笔日付申请未通过总经理审核";
                    info.ResultColor = "warning";
                }
            }
            else if (fin_DailyFeePayment.FAudit == 2)
            {
                info.AuditDate = fin_DailyFeePayment.FAuditDate.ToString("yyyy-MM-dd HH:mm");
                info.Result = "你有一笔日付申请未通过财务审核";
                info.ResultColor = "warning";
            }
            List<string> qwUserIdList = GetQiyeChatUserIdList(userId);
            if (qwUserIdList.Count > 0)
            {
                ResponseBase result = await _qiYeWeChatApiService.GroupStatus_SendMessage_ToUser_Markdown(qwUserIdList, MarkdownLib.DailyPayReminder_Audit_ToUser(info));
                if (result.errcode != 0)
                {
                    //抄送日志 
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 日付申请已付款推送给申请人
        /// </summary>
        /// <returns></returns>
        public static async Task<bool> DailyPayReminder_Pay_ToUser(int dailyPayId, List<string> userId)
        {
            Fin_DailyFeePayment fin_DailyFeePayment = _grpDeleRep.Query<Fin_DailyFeePayment>(s => s.Id == dailyPayId).First();
            string priceStr = fin_DailyFeePayment.SumPrice.ToString("#0.00");

            DailyPayReminder_Pay_ToUserModel info = new DailyPayReminder_Pay_ToUserModel()
            {
                PayDt = DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
                PriceName = fin_DailyFeePayment.Instructions,
                Price = priceStr
            };
            List<string> qwUserIdList = GetQiyeChatUserIdList(userId);
            if (qwUserIdList.Count > 0)
            {
                ResponseBase result = await _qiYeWeChatApiService.GroupStatus_SendMessage_ToUser_Markdown(qwUserIdList, MarkdownLib.DailyPayReminder_Pay_ToUser(info));
                if (result.errcode != 0)
                {
                    //抄送日志 
                    return false;
                }
            }
            return true;
        }

        #endregion

        #region 成本通知

        /// <summary>
        /// 成本通知发送给对应岗位用户
        /// </summary>
        /// <param name="diId"></param>
        /// <returns></returns>
        public static async Task<bool> SendUserMsg_GroupShare_ToJob(int diId)
        {
            Grp_DelegationInfo groupInfo = _grpDeleRep.Query<Grp_DelegationInfo>(s => s.Id == diId).First();
            List<Sys_Users> list_user = _grpDeleRep.Query<Sys_Users>(s => s.IsDel == 0 && (s.JobPostId == 24 || s.JobPostId == 25 || s.JobPostId == 28)).ToList();
            //List<Sys_Users> list_user = _grpDeleRep.Query<Sys_Users>(s => s.IsDel == 0 && (s.JobPostId == 40 || s.JobPostId == 41)).ToList();
            List<string> userIds = new List<string>();
            list_user.ForEach(s => userIds.Add(s.Id.ToString()));
            List<string> qwUserIdList = GetQiyeChatUserIdList(userIds);

            GroupShare_ToUserModel info = new GroupShare_ToUserModel()
            {
                RefreshDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
                TeamName = groupInfo.TeamName
            };

            if (qwUserIdList.Count > 0)
            {
                ResponseBase result = await _qiYeWeChatApiService.GroupStatus_SendMessage_ToUser_Markdown(qwUserIdList, MarkdownLib.GroupShare_ToUser(info));
                if (result.errcode != 0)
                {
                    //抄送日志 
                    return false;
                }
            }

            return true;
        }


        #endregion

        #region Helper

        private static string getClientNameStr(List<SimplClientInfo> list, string origin)
        {
            string result = origin;

            if (Regex.Match(origin, @"\d+,?").Value.Length > 0)
            {
                string[] temparr = origin.Split(',');
                string fistrStr = temparr[0];
                int count = temparr.Count();

                int tempId;
                bool success = int.TryParse(fistrStr, out tempId);
                if (success)
                {
                    SimplClientInfo tempInfo = list.FirstOrDefault(s => s.Id == tempId);
                    if (tempInfo != null)
                    {
                        if (count > 1)
                        {
                            result = string.Format(@"{0}{1}等{2}人", tempInfo.LastName, tempInfo.FirstName, count);
                        }
                        else
                        {
                            result = string.Format(@"{0}{1}", tempInfo.LastName, tempInfo.FirstName);
                        }
                    }
                }
            }

            return result;
        }

        private static List<SimplClientInfo> getSimplClientList(int diId)
        {
            string sql = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from  Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", diId);
            List<SimplClientInfo> arr = _grpDeleRep._sqlSugar.SqlQueryable<SimplClientInfo>(sql).ToList();
            return arr;
        }

        #endregion

    }
}
