using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using Edu.Cache.WeChat;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.WeChat;
using Edu.Module.QYWeChat;
using Edu.ThirdCore.QYWinXin;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.QYWeChat
{
    /// <summary>
    /// 企业微信回调接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    public class QYWeChatCallBackController : ControllerBase
    {
        /// <summary>
        /// 企业微信处理类对象
        /// </summary>
        private readonly QYWeChatModule weChatModule = new QYWeChatModule();
        /// <summary>
        /// 客户处理类
        /// </summary>
        //private readonly QYCustomerModule customerModule = new QYCustomerModule();

        #region 欢迎语管理

        /// <summary>
        /// 欢迎语回调
        /// </summary>
        [HttpGet]
        public string WeChatReceiveCustomerAdd(int groupId,string msg_signature,string timestamp,string nonce,string echostr) {
            //首先获取配置
            var model = weChatModule.GetWeChatConfigModel(new RB_WeChat_Config_ViewModel() { Group_Id = groupId });
            if (model == null || model.Id == 0 || model.Enable !=1) { return ""; }

            Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(model.Token, model.Encoding_Aes_Key, model.WX_CorpId);
            string sVerifyMsgSig = msg_signature;
            string sVerifyTimeStamp = timestamp;
            string sVerifyNonce = nonce;
            string sVerifyEchoStr = echostr;
            int ret = 0;
            string sEchoStr = "";
            ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr);
            if (ret != 0)
            {
                LogHelper.Write("验证Url失败：" + ret);
                return "";
            }

            return sEchoStr;
        }

        /// <summary>
        /// 欢迎语回调
        /// </summary>
        [HttpPost]
        public string WeChatReceiveCustomerAdd(int groupId,string msg_signature,string timestamp, string nonce)
        {
            //首先获取配置
            var configmodel = weChatModule.GetWeChatConfigModel(new RB_WeChat_Config_ViewModel() { Group_Id = groupId }).RefMapperTo<RB_WeChat_Config_ViewModel>();
            if (configmodel == null || configmodel.Id == 0 || configmodel.Enable != 1) { return ""; }

            string sReqMsgSig = msg_signature;
            string sReqTimeStamp = timestamp;
            string sReqNonce = nonce;
            #region Post请求的密文数据
            Request.EnableBuffering();
            string responseData = "";
            using (var reader = new StreamReader(Request.Body, encoding: System.Text.Encoding.UTF8))
            {
                var body = reader.ReadToEndAsync();
                responseData = body.Result;
                Request.Body.Position = 0;
            }
            #endregion

            #region 解码参数
            string sReqData = responseData;
            string sMsg = "";  // 解析之后的明文
            Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(configmodel.Token, configmodel.Encoding_Aes_Key, configmodel.WX_CorpId);
            int ret = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData, ref sMsg);
            if (ret != 0)
            {
                LogHelper.Write("解密失败：" + ret);
                return "";
            }
            LogHelper.Write(sMsg);
            // ret==0表示解密成功，sMsg表示解密之后的明文xml串
            // TODO: 对明文的处理
            // For example:
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(sMsg);
            XmlNode root = doc.FirstChild;
            string ToUserName = root["ToUserName"].InnerText;
            string FromUserName = root["FromUserName"].InnerText;
            string MsgType = root["MsgType"].InnerText;
            string Event = root["Event"].InnerText;
            string ChangeType = root["ChangeType"].InnerText;
            string UserID = root["UserID"].InnerText;
            string ExternalUserID = root["ExternalUserID"].InnerText;
            string State = root["State"]?.InnerText ?? "";
            string WelcomeCode = root["WelcomeCode"]?.InnerText ?? "";
            #endregion
            
            //处理新添加客人事件
            if (!string.IsNullOrEmpty(WelcomeCode) && MsgType == "event" && Event == "change_external_contact" && ChangeType == "add_external_contact")
            {
                #region 正常推送
                //获取token
                string token = GetContactToken(groupId, configmodel);
                if (string.IsNullOrEmpty(token)) { return ""; }
                //根据WXUserId  获取对应系统用户
                var empModel = weChatModule.GetUserInfoForWeiXinWorkUserId(groupId, UserID);

                if (!string.IsNullOrEmpty(State) && State.Contains("ChannelId="))
                {
                    try
                    {
                        //从渠道码进来的
                        int ChannelId = Convert.ToInt32(State.Split("=")[1]);
                        if (ChannelId > 0)
                        {
                            var channelModel = weChatModule.GetWeChatChannelForBackUp(ChannelId);
                            if (channelModel == null) { return ""; }

                            var ContactModel = QYWeiXinHelper.GetExternalContactInfo(token, ExternalUserID);
                            if (ContactModel.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                            {
                                LogHelper.Write("获取客户信息失败：" + ContactModel.errmsg);
                            }

                            #region 推送欢迎语
                            RB_WeChat_Welcomes_ViewModel welcomeModel = new RB_WeChat_Welcomes_ViewModel();
                            DateTime NowDate = DateTime.Now;
                            DateTime NowDay = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                            string NowDateStr = DateTime.Now.ToString("yyyy-MM-dd");
                            bool IsChannelWelcome = false;
                            if (channelModel.WelcomeEnable == 1)
                            {
                                if (channelModel.WelcomeSpecialEnable == 1)
                                {
                                    var swlist = channelModel.WelcomeSpecialList.Where(x => x.StartDate <= NowDay && x.EndDate >= NowDay && Convert.ToDateTime(NowDateStr + " " + x.StartHours) <= NowDate && Convert.ToDateTime(NowDateStr + " " + x.EndHours) >= NowDate).ToList();
                                    if (swlist.Any())
                                    {
                                        var swmodel = swlist.FirstOrDefault();
                                        welcomeModel.Type = string.IsNullOrEmpty(swmodel.MediumIds) ? 1 : 2;
                                        welcomeModel.Content = swmodel.Content;
                                        welcomeModel.MediumIds = swmodel.MediumIds;
                                        welcomeModel.MediumList = swmodel.MediumList;
                                    }
                                }
                                if (welcomeModel.Type == 0 && channelModel.WelcomeWeekEnable == 1)
                                {
                                    //查询正常周期配置
                                    string weekNum = "," + (int)DateTime.Now.DayOfWeek + ",";
                                    var wlist = channelModel.WelcomeWeekList.Where(x => ("," + x.Weeks + ",").Contains(weekNum) && Convert.ToDateTime(NowDateStr + " " + x.StartHours) <= NowDate && Convert.ToDateTime(NowDateStr + " " + x.EndHours) >= NowDate).ToList();
                                    if (wlist.Any())
                                    {
                                        var swmodel = wlist.FirstOrDefault();
                                        welcomeModel.Type = string.IsNullOrEmpty(swmodel.MediumIds) ? 1 : 2;
                                        welcomeModel.Content = swmodel.Content;
                                        welcomeModel.MediumIds = swmodel.MediumIds;
                                        welcomeModel.MediumList = swmodel.MediumList;
                                    }
                                }
                                if (welcomeModel.Type == 0)
                                {
                                    var swlist = channelModel.WelcomeList;
                                    if (swlist.Any())
                                    {
                                        var swmodel = swlist.FirstOrDefault();
                                        welcomeModel.Type = string.IsNullOrEmpty(swmodel.MediumIds) ? 1 : 2;
                                        welcomeModel.Content = swmodel.Content;
                                        welcomeModel.MediumIds = swmodel.MediumIds;
                                        welcomeModel.MediumList = swmodel.MediumList;
                                    }
                                }

                                if (welcomeModel.Type > 0)
                                {
                                    IsChannelWelcome = true;
                                    //推送欢迎语
                                    if (welcomeModel.Content.Contains("##客户名称##"))
                                    {
                                        //替换客户名称
                                        string ContactName = ContactModel?.external_contact?.name ?? "";
                                        welcomeModel.Content = welcomeModel.Content.Replace("##客户名称##", ContactName);
                                    }
                                    if (welcomeModel.Content.Contains("##员工姓名##"))
                                    {
                                        //替换员工姓名
                                        welcomeModel.Content = welcomeModel.Content.Replace("##员工姓名##", empModel.EmployeeName);
                                    }
                                    if (welcomeModel.Content.Contains("##员工别名##"))
                                    {
                                        //替换客户名称
                                        var MemberModel = QYWeiXinHelper.GetMember_V2(token, UserID);
                                        string Alias = MemberModel?.alias ?? "";

                                        welcomeModel.Content = welcomeModel.Content.Replace("##员工别名##", Alias);
                                    }
                                    //开始状态欢迎语  掉推送接口
                                    string RMsg = weChatModule.SendNewCustomerWelcome(token, WelcomeCode, welcomeModel);
                                    //处理消息
                                    if (!string.IsNullOrEmpty(RMsg))
                                    {
                                        JObject parms = JObject.Parse(RMsg);
                                        int errcode = parms.GetInt("errcode");
                                        if (errcode != 0)
                                        {
                                            string errmsg = parms.GetStringValue("errmsg");
                                            LogHelper.Write("推送欢迎语失败：" + errmsg);
                                        }
                                    }
                                }
                            }
                            if (!IsChannelWelcome)
                            {
                                //获取欢迎语列表  使用通用配置的欢迎语
                                var WelcomeList = weChatModule.GetWeChatWelcomesList(new RB_WeChat_Welcomes_ViewModel() { Group_Id = groupId, UserId = empModel.Id });
                                if (WelcomeList.Any())
                                {
                                    if (WelcomeList.Where(x => x.UserIds != "-1").Any())
                                    {
                                        WelcomeList = WelcomeList.Where(x => x.UserIds != "-1").ToList();//优先使用配置人员的  再使用通用的
                                    }
                                    //多个欢迎语  默认取最新的
                                    welcomeModel = WelcomeList.FirstOrDefault();
                                    if (welcomeModel.Content.Contains("##客户名称##"))
                                    {
                                        //替换客户名称
                                        string ContactName = ContactModel?.external_contact?.name ?? "";

                                        welcomeModel.Content = welcomeModel.Content.Replace("##客户名称##", ContactName);
                                    }
                                    if (welcomeModel.Content.Contains("##员工姓名##"))
                                    {
                                        //替换员工姓名
                                        welcomeModel.Content = welcomeModel.Content.Replace("##员工姓名##", empModel.EmployeeName);
                                    }
                                    if (welcomeModel.Content.Contains("##员工别名##"))
                                    {
                                        //替换客户名称
                                        var MemberModel = QYWeiXinHelper.GetMember_V2(token, UserID);
                                        string Alias = MemberModel?.alias ?? "";

                                        welcomeModel.Content = welcomeModel.Content.Replace("##员工别名##", Alias);
                                    }
                                    //开始状态欢迎语  掉推送接口
                                    string RMsg = weChatModule.SendNewCustomerWelcome(token, WelcomeCode, welcomeModel);
                                    //处理消息
                                    if (!string.IsNullOrEmpty(RMsg))
                                    {
                                        JObject parms = JObject.Parse(RMsg);
                                        int errcode = parms.GetInt("errcode");
                                        if (errcode != 0)
                                        {
                                            string errmsg = parms.GetStringValue("errmsg");
                                            LogHelper.Write("推送欢迎语失败：" + errmsg);
                                        }
                                    }
                                }
                            }
                            #endregion

                            #region 给客户打标签
                            if (channelModel.LabelList != null && channelModel.LabelList.Any())
                            {
                                var lmsg = QYWeiXinHelper.SetUserCoustmerLable(token, UserID, ExternalUserID, channelModel.LabelList);
                                if (lmsg.errcode != Senparc.Weixin.ReturnCode_Work.请求成功) {
                                    LogHelper.Write("记录客户标记失败：" + lmsg.errmsg);
                                }
                            }
                            #endregion

                            #region 添加客户记录

                            weChatModule.AddWeChatClientRecord(new RB_WeChat_ChannelRecord_ViewModel()
                            {
                                Id = 0,
                                ChannelId = ChannelId,
                                CreateBy = 1,
                                CreateTime = DateTime.Now,
                                CustomerNum = 0,
                                EmpId = (empModel?.Id ?? 0),
                                ExternalUserId = ExternalUserID,
                                CustomerName = ContactModel?.external_contact?.name ?? "",
                                Group_Id = channelModel.Group_Id,
                                Status = 0,
                                Type = 1,
                                UpdateBy = 1,
                                UpdateTime = DateTime.Now,
                                WorkEmpId = UserID
                            });
                            #endregion

                            #region 添加人员限制
                            bool IsLimit = false;
                            //人员添加记录
                            if (channelModel.EmpAddLimit == 1 && channelModel.LimitList.Any())
                            {
                                var limitModel = channelModel.LimitList.Where(x => x.EmpId == (empModel?.Id ?? -1)).FirstOrDefault();
                                if (limitModel != null)
                                {
                                    limitModel.ClientNum++;
                                    weChatModule.UpdateWeChatLimitClientNum(limitModel);
                                    if (limitModel.LimitNum > 0 && limitModel.LimitNum <= limitModel.ClientNum)
                                    {
                                        IsLimit = true;//已经添加满了
                                    }
                                }
                            }

                            //如果人员已添加满  需更新渠道码 重新定义用户
                            if (IsLimit)
                            {
                                var Rmsg = weChatModule.UpdateContactWayForQYWeiXin(channelModel, configmodel, true);
                                if (Rmsg.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                                {
                                    LogHelper.Write("添加客户回调(" + channelModel.Id + ")更新渠道码失败，" + Rmsg.errmsg);
                                }
                            }
                            #endregion
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Write(ex, "WeChatReceiveCustomerAdd");
                    }                    
                }
                else
                {
                    #region 正常的添加客户好友
                    if (empModel == null) { return ""; }
                    //获取欢迎语列表
                    var WelcomeList = weChatModule.GetWeChatWelcomesList(new RB_WeChat_Welcomes_ViewModel() { Group_Id = groupId, UserId = empModel.Id });
                    if (WelcomeList.Any())
                    {
                        if (WelcomeList.Where(x => x.UserIds != "-1").Any())
                        {
                            WelcomeList = WelcomeList.Where(x => x.UserIds != "-1").ToList();//优先使用配置人员的  再使用通用的
                        }
                        //多个欢迎语  默认取最新的
                        var welcomeModel = WelcomeList.FirstOrDefault();
                        if (welcomeModel.Content.Contains("##客户名称##"))
                        {
                            //替换客户名称
                            var ContactModel = QYWeiXinHelper.GetExternalContactInfo(token, ExternalUserID);
                            string ContactName = ContactModel?.external_contact?.name ?? "";

                            welcomeModel.Content = welcomeModel.Content.Replace("##客户名称##", ContactName);
                        }
                        if (welcomeModel.Content.Contains("##员工姓名##"))
                        {
                            //替换员工姓名
                            welcomeModel.Content = welcomeModel.Content.Replace("##员工姓名##", empModel.EmployeeName);
                        }
                        if (welcomeModel.Content.Contains("##员工别名##"))
                        {
                            //替换客户名称
                            var MemberModel = QYWeiXinHelper.GetMember_V2(token, UserID);
                            string Alias = MemberModel?.alias ?? "";

                            welcomeModel.Content = welcomeModel.Content.Replace("##员工别名##", Alias);
                        }
                        //开始状态欢迎语  掉推送接口
                        string RMsg = weChatModule.SendNewCustomerWelcome(token, WelcomeCode, welcomeModel);
                        //处理消息
                        if (!string.IsNullOrEmpty(RMsg))
                        {
                            JObject parms = JObject.Parse(RMsg);
                            int errcode = parms.GetInt("errcode");
                            if (errcode != 0)
                            {
                                string errmsg = parms.GetStringValue("errmsg");
                                LogHelper.Write("推送欢迎语失败：" + errmsg);
                            }
                        }
                    }
                    #endregion
                }
                #endregion
            }
            //成员删除外部联系人时 / 成员被外部联系人删除时
            else if (MsgType == "event" && Event == "change_external_contact" && (ChangeType == "del_external_contact" || ChangeType == "del_follow_user"))
            {
                int ChannelId = 0;
                if (!string.IsNullOrEmpty(State) && State.Contains("ChannelId="))
                {
                    ChannelId = Convert.ToInt32(State.Split("=")[1]);
                }
                else
                {
                    //根据员工 + 客人的企业微信Id 获取新增记录
                    var recordModel = weChatModule.GeetWeChatClientRecord(groupId, UserID, ExternalUserID);
                    ChannelId = recordModel?.ChannelId ?? 0;
                }

                //根据WXUserId  获取对应系统用户
                var empModel = weChatModule.GetUserInfoForWeiXinWorkUserId(groupId, UserID);
                //获取token
                string token = GetContactToken(groupId, configmodel);
                if (string.IsNullOrEmpty(token)) { return ""; }
                var ContactModel = QYWeiXinHelper.GetExternalContactInfo(token, ExternalUserID);
                if (ContactModel.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                {
                    LogHelper.Write("获取客户信息失败：" + ContactModel.errmsg);
                }
                weChatModule.AddWeChatClientRecord(new RB_WeChat_ChannelRecord_ViewModel()
                {
                    Id = 0,
                    ChannelId = ChannelId,
                    CreateBy = 1,
                    CreateTime = DateTime.Now,
                    CustomerNum = 0,
                    EmpId = (empModel?.Id ?? 0),
                    ExternalUserId = ExternalUserID,
                    CustomerName = ContactModel?.external_contact?.name ?? "",
                    Group_Id = groupId,
                    Status = 0,
                    Type = ChangeType == "del_external_contact" ? 3 : 2,
                    UpdateBy = 1,
                    UpdateTime = DateTime.Now,
                    WorkEmpId = UserID
                });

                //更新客户信息  好友状态为待添加
                //if (ChangeType == "del_external_contact") {
                //    System.Threading.Tasks.Task.Run(() => customerModule.UpdateCustomerFriendStateForBack(UserID, ExternalUserID, groupId));
                //}
            }

            //任务记录客户明细信息
            //if (MsgType == "event" && Event == "change_external_contact" && ChangeType == "add_external_contact")
            //{
            //    System.Threading.Tasks.Task.Run(() => customerModule.AddCustomerInfoForBack(UserID, ExternalUserID, State, groupId));
            //}

            //客户交替失败事件
            //if (MsgType == "event" && Event == "change_external_contact" && ChangeType == "transfer_fail") { 
                
            //}
            return "";
        }

        /// <summary>
        /// 获取外部联系人token
        /// </summary>
        /// <param name="Group_Id"></param>
        /// <param name="configmodel"></param>
        /// <returns></returns>
        private string GetContactToken(int Group_Id, RB_WeChat_Config_ViewModel configmodel)
        {
            string token = WeChatReidsCache.GetToken(Cache.CacheKey.QYWeChat_EmpToken_Key + Group_Id);
            if (string.IsNullOrEmpty(token))
            {
                var TelToken = QYWeiXinHelper.GetToken(configmodel.WX_CorpId, configmodel.Contact_Secret);
                if (TelToken.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                {
                    WeChatReidsCache.TokenSet(Cache.CacheKey.QYWeChat_EmpToken_Key + Group_Id, TelToken.access_token, TelToken.expires_in - 1);
                    token = TelToken.access_token;
                }
                else
                {
                    LogHelper.Write("token获取失败，" + TelToken.errmsg);
                    return "";
                }
            }
            return token;
        }

        /// <summary>
        /// 测试推送
        /// </summary>
        /// <returns></returns>
        public string WeChatReceiveCustomerAddTest(int groupId)
        {
            //首先获取配置
            var configmodel = weChatModule.GetWeChatConfigModel(new RB_WeChat_Config_ViewModel() { Group_Id = groupId }).RefMapperTo<RB_WeChat_Config_ViewModel>();
            if (configmodel == null) { return ""; }

            string sMsg = "<xml><ToUserName><![CDATA[ww2f612caf0cc698a0]]></ToUserName><FromUserName><![CDATA[sys]]></FromUserName><CreateTime>1629442351</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[change_external_contact]]></Event><ChangeType><![CDATA[add_external_contact]]></ChangeType><UserID><![CDATA[JinCiDianErYi]]></UserID><ExternalUserID><![CDATA[wmLiGADQAAipPmemFEirDdBD_ThZfEJw]]></ExternalUserID><State><![CDATA[ChannelId=20]]></State><WelcomeCode><![CDATA[UEMbBgD5JDrADeE_-uLY20YZDWAZPsVHj7eYL1R_Xfg]]></WelcomeCode></xml>";

            #region 解码参数
            // ret==0表示解密成功，sMsg表示解密之后的明文xml串
            // TODO: 对明文的处理
            // For example:
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(sMsg);
            XmlNode root = doc.FirstChild;
            string ToUserName = root["ToUserName"].InnerText;
            string FromUserName = root["FromUserName"].InnerText;
            string MsgType = root["MsgType"].InnerText;
            string Event = root["Event"].InnerText;
            string ChangeType = root["ChangeType"].InnerText;
            string UserID = root["UserID"].InnerText;
            string ExternalUserID = root["ExternalUserID"].InnerText;
            string State = root["State"]?.InnerText ?? "";
            string WelcomeCode = root["WelcomeCode"]?.InnerText ?? "";
            #endregion

            #region 欢迎语
            //处理新添加客人事件  add_half_external_contact(这个事件需注意)
            //if (!string.IsNullOrEmpty(WelcomeCode) && MsgType == "event" && Event == "change_external_contact" && ChangeType == "add_external_contact")
            //{
            //    #region 正常推送
            //    //获取token
            //    string token = GetContactToken(groupId, configmodel);
            //    if (string.IsNullOrEmpty(token)) { return ""; }
            //    //根据WXUserId  获取对应系统用户
            //    var empModel = weChatModule.GetUserInfoForWeiXinWorkUserId(groupId, UserID);

            //    if (!string.IsNullOrEmpty(State) && State.Contains("ChannelId="))
            //    {
            //        try
            //        {
            //            //从渠道码进来的
            //            int ChannelId = Convert.ToInt32(State.Split("=")[1]);
            //            if (ChannelId > 0)
            //            {
            //                var channelModel = weChatModule.GetWeChatChannelForBackUp(ChannelId);
            //                if (channelModel == null) { return ""; }

            //                var ContactModel = QYWeiXinHelper.GetExternalContactInfo(token, ExternalUserID);
            //                if (ContactModel.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
            //                {
            //                    LogHelper.Write("获取客户信息失败：" + ContactModel.errmsg);
            //                }

            //                #region 推送欢迎语
            //                RB_WeChat_Welcomes_ViewModel welcomeModel = new RB_WeChat_Welcomes_ViewModel();
            //                DateTime NowDate = DateTime.Now;
            //                DateTime NowDay = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
            //                string NowDateStr = DateTime.Now.ToString("yyyy-MM-dd");
            //                bool IsChannelWelcome = false;
            //                if (channelModel.WelcomeEnable == 1)
            //                {
            //                    if (channelModel.WelcomeSpecialEnable == 1)
            //                    {
            //                        var swlist = channelModel.WelcomeSpecialList.Where(x => x.StartDate <= NowDay && x.EndDate >= NowDay && Convert.ToDateTime(NowDateStr + " " + x.StartHours) <= NowDate && Convert.ToDateTime(NowDateStr + " " + x.EndHours) >= NowDate).ToList();
            //                        if (swlist.Any())
            //                        {
            //                            var swmodel = swlist.FirstOrDefault();
            //                            welcomeModel.Type = string.IsNullOrEmpty(swmodel.MediumIds) ? 1 : 2;
            //                            welcomeModel.Content = swmodel.Content;
            //                            welcomeModel.MediumIds = swmodel.MediumIds;
            //                            welcomeModel.MediumList = swmodel.MediumList;
            //                        }
            //                    }
            //                    if (welcomeModel.Type == 0 && channelModel.WelcomeWeekEnable == 1)
            //                    {
            //                        //查询正常周期配置
            //                        string weekNum = "," + (int)DateTime.Now.DayOfWeek + ",";
            //                        var wlist = channelModel.WelcomeWeekList.Where(x => ("," + x.Weeks + ",").Contains(weekNum) && Convert.ToDateTime(NowDateStr + " " + x.StartHours) <= NowDate && Convert.ToDateTime(NowDateStr + " " + x.EndHours) >= NowDate).ToList();
            //                        if (wlist.Any())
            //                        {
            //                            var swmodel = wlist.FirstOrDefault();
            //                            welcomeModel.Type = string.IsNullOrEmpty(swmodel.MediumIds) ? 1 : 2;
            //                            welcomeModel.Content = swmodel.Content;
            //                            welcomeModel.MediumIds = swmodel.MediumIds;
            //                            welcomeModel.MediumList = swmodel.MediumList;
            //                        }
            //                    }
            //                    if (welcomeModel.Type == 0)
            //                    {
            //                        var swlist = channelModel.WelcomeList;
            //                        if (swlist.Any())
            //                        {
            //                            var swmodel = swlist.FirstOrDefault();
            //                            welcomeModel.Type = string.IsNullOrEmpty(swmodel.MediumIds) ? 1 : 2;
            //                            welcomeModel.Content = swmodel.Content;
            //                            welcomeModel.MediumIds = swmodel.MediumIds;
            //                            welcomeModel.MediumList = swmodel.MediumList;
            //                        }
            //                    }

            //                    if (welcomeModel.Type > 0)
            //                    {
            //                        IsChannelWelcome = true;
            //                        //推送欢迎语
            //                        if (welcomeModel.Content.Contains("##客户名称##"))
            //                        {
            //                            //替换客户名称
            //                            string ContactName = ContactModel?.external_contact?.name ?? "";
            //                            welcomeModel.Content = welcomeModel.Content.Replace("##客户名称##", ContactName);
            //                        }
            //                        //开始状态欢迎语  掉推送接口
            //                        string RMsg = weChatModule.SendNewCustomerWelcome(token, WelcomeCode, welcomeModel);
            //                        //处理消息
            //                        if (!string.IsNullOrEmpty(RMsg))
            //                        {
            //                            JObject parms = JObject.Parse(RMsg);
            //                            int errcode = parms.GetInt("errcode");
            //                            if (errcode != 0)
            //                            {
            //                                string errmsg = parms.GetStringValue("errmsg");
            //                                LogHelper.Write("推送欢迎语失败：" + errmsg);
            //                            }
            //                        }
            //                    }
            //                }
            //                if (!IsChannelWelcome)
            //                {
            //                    //获取欢迎语列表  使用通用配置的欢迎语
            //                    var WelcomeList = weChatModule.GetWeChatWelcomesList(new RB_WeChat_Welcomes_ViewModel() { Group_Id = groupId, UserId = empModel.Id });
            //                    if (WelcomeList.Any())
            //                    {
            //                        if (WelcomeList.Where(x => x.UserIds != "-1").Any())
            //                        {
            //                            WelcomeList = WelcomeList.Where(x => x.UserIds != "-1").ToList();//优先使用配置人员的  再使用通用的
            //                        }
            //                        //多个欢迎语  默认取最新的
            //                        welcomeModel = WelcomeList.FirstOrDefault();
            //                        if (welcomeModel.Content.Contains("##客户名称##"))
            //                        {
            //                            //替换客户名称
            //                            string ContactName = ContactModel?.external_contact?.name ?? "";

            //                            welcomeModel.Content = welcomeModel.Content.Replace("##客户名称##", ContactName);
            //                        }
            //                        //开始状态欢迎语  掉推送接口
            //                        string RMsg = weChatModule.SendNewCustomerWelcome(token, WelcomeCode, welcomeModel);
            //                        //处理消息
            //                        if (!string.IsNullOrEmpty(RMsg))
            //                        {
            //                            JObject parms = JObject.Parse(RMsg);
            //                            int errcode = parms.GetInt("errcode");
            //                            if (errcode != 0)
            //                            {
            //                                string errmsg = parms.GetStringValue("errmsg");
            //                                LogHelper.Write("推送欢迎语失败：" + errmsg);
            //                            }
            //                        }
            //                    }
            //                }
            //                #endregion

            //                #region 给客户打标签
            //                if (channelModel.LabelList != null && channelModel.LabelList.Any())
            //                {
            //                    var lmsg = QYWeiXinHelper.SetUserCoustmerLable(token, UserID, ExternalUserID, channelModel.LabelList);
            //                    if (lmsg.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
            //                    {
            //                        LogHelper.Write("记录客户标记失败：" + lmsg.errmsg);
            //                    }
            //                }
            //                #endregion

            //                #region 添加客户记录

            //                weChatModule.AddWeChatClientRecord(new RB_WeChat_ChannelRecord_ViewModel()
            //                {
            //                    Id = 0,
            //                    ChannelId = ChannelId,
            //                    CreateBy = 1,
            //                    CreateTime = DateTime.Now,
            //                    CustomerNum = 0,
            //                    EmpId = (empModel?.Id ?? 0),
            //                    ExternalUserId = ExternalUserID,
            //                    CustomerName = ContactModel?.external_contact?.name ?? "",
            //                    Group_Id = channelModel.Group_Id,
            //                    Status = 0,
            //                    Type = 1,
            //                    UpdateBy = 1,
            //                    UpdateTime = DateTime.Now,
            //                    WorkEmpId = UserID
            //                });
            //                #endregion

            //                #region 添加人员限制
            //                bool IsLimit = false;
            //                //人员添加记录
            //                if (channelModel.EmpAddLimit == 1 && channelModel.LimitList.Any())
            //                {
            //                    var limitModel = channelModel.LimitList.Where(x => x.EmpId == (empModel?.Id ?? -1)).FirstOrDefault();
            //                    if (limitModel != null)
            //                    {
            //                        limitModel.ClientNum++;
            //                        weChatModule.UpdateWeChatLimitClientNum(limitModel);
            //                        if (limitModel.LimitNum > 0 && limitModel.LimitNum <= limitModel.ClientNum)
            //                        {
            //                            IsLimit = true;//已经添加满了
            //                        }
            //                    }
            //                }

            //                //如果人员已添加满  需更新渠道码 重新定义用户
            //                if (IsLimit)
            //                {
            //                    var Rmsg = weChatModule.UpdateContactWayForQYWeiXin(channelModel, configmodel, true);
            //                    if (Rmsg.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
            //                    {
            //                        LogHelper.Write("添加客户回调(" + channelModel.Id + ")更新渠道码失败，" + Rmsg.errmsg);
            //                    }
            //                }
            //                #endregion
            //            }
            //        }
            //        catch (Exception ex)
            //        {
            //            LogHelper.Write(ex, "WeChatReceiveCustomerAdd");
            //        }
            //    }
            //    else
            //    {
            //        #region 正常的添加客户好友
            //        if (empModel == null) { return ""; }
            //        //获取欢迎语列表
            //        var WelcomeList = weChatModule.GetWeChatWelcomesList(new RB_WeChat_Welcomes_ViewModel() { Group_Id = groupId, UserId = empModel.Id });
            //        if (WelcomeList.Any())
            //        {
            //            if (WelcomeList.Where(x => x.UserIds != "-1").Any())
            //            {
            //                WelcomeList = WelcomeList.Where(x => x.UserIds != "-1").ToList();//优先使用配置人员的  再使用通用的
            //            }
            //            //多个欢迎语  默认取最新的
            //            var welcomeModel = WelcomeList.FirstOrDefault();
            //            if (welcomeModel.Content.Contains("##客户名称##"))
            //            {
            //                //替换客户名称
            //                var ContactModel = QYWeiXinHelper.GetExternalContactInfo(token, ExternalUserID);
            //                string ContactName = ContactModel?.external_contact?.name ?? "";

            //                welcomeModel.Content = welcomeModel.Content.Replace("##客户名称##", ContactName);
            //            }
            //            //开始状态欢迎语  掉推送接口
            //            string RMsg = weChatModule.SendNewCustomerWelcome(token, WelcomeCode, welcomeModel);
            //            //处理消息
            //            if (!string.IsNullOrEmpty(RMsg))
            //            {
            //                JObject parms = JObject.Parse(RMsg);
            //                int errcode = parms.GetInt("errcode");
            //                if (errcode != 0)
            //                {
            //                    string errmsg = parms.GetStringValue("errmsg");
            //                    LogHelper.Write("推送欢迎语失败：" + errmsg);
            //                }
            //            }
            //        }
            //        #endregion
            //    }
            //    #endregion
            //}
            ////成员删除外部联系人时 / 成员被外部联系人删除时
            //else if (MsgType == "event" && Event == "change_external_contact" && (ChangeType == "del_external_contact" || ChangeType == "del_follow_user"))
            //{
            //    int ChannelId = 0;
            //    if (!string.IsNullOrEmpty(State) && State.Contains("ChannelId="))
            //    {
            //        ChannelId = Convert.ToInt32(State.Split("=")[1]);
            //    }
            //    else
            //    {
            //        //根据员工 + 客人的企业微信Id 获取新增记录
            //        var recordModel = weChatModule.GeetWeChatClientRecord(groupId, UserID, ExternalUserID);
            //        ChannelId = recordModel?.ChannelId ?? 0;
            //    }

            //    //根据WXUserId  获取对应系统用户
            //    var empModel = weChatModule.GetUserInfoForWeiXinWorkUserId(groupId, UserID);
            //    //获取token
            //    string token = GetContactToken(groupId, configmodel);
            //    if (string.IsNullOrEmpty(token)) { return ""; }
            //    var ContactModel = QYWeiXinHelper.GetExternalContactInfo(token, ExternalUserID);
            //    if (ContactModel.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
            //    {
            //        LogHelper.Write("获取客户信息失败：" + ContactModel.errmsg);
            //    }
            //    weChatModule.AddWeChatClientRecord(new RB_WeChat_ChannelRecord_ViewModel()
            //    {
            //        Id = 0,
            //        ChannelId = ChannelId,
            //        CreateBy = 1,
            //        CreateTime = DateTime.Now,
            //        CustomerNum = 0,
            //        EmpId = (empModel?.Id ?? 0),
            //        ExternalUserId = ExternalUserID,
            //        CustomerName = ContactModel?.external_contact?.name ?? "",
            //        Group_Id = groupId,
            //        Status = 0,
            //        Type = ChangeType == "del_external_contact" ? 3 : 2,
            //        UpdateBy = 1,
            //        UpdateTime = DateTime.Now,
            //        WorkEmpId = UserID
            //    });
            //}
            #endregion

            //任务记录客户明细信息
            //if (MsgType == "event" && Event == "change_external_contact" && ChangeType == "add_external_contact")
            //{
            //    System.Threading.Tasks.Task.Run(() => customerModule.AddCustomerInfoForBack(UserID, ExternalUserID, State, groupId));
            //}
            return "";
        }

        #endregion
    }
}
