using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Edu.Cache.WeChat;
using Edu.Common;
using Edu.Common.API;
using Edu.Common.Enum.Finance;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.User;
using Edu.Model.ViewModel.WeChat;
using Edu.Repository.User;
using Edu.Repository.WeChat;
using Edu.ThirdCore.QYWinXin;
using Edu.ThirdCore.QYWinXin.Model;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.Work.AdvancedAPIs.OAuth2;
using VT.FW.DB;

namespace Edu.Module.QYWeChat
{
    /// <summary>
    /// 企业微信处理类
    /// </summary>
    public class QYWeChatModule
    {
        /// <summary>
        /// 微信配置
        /// </summary>
        private readonly RB_WeChat_ConfigRepository weChat_ConfigRepository = new RB_WeChat_ConfigRepository();
        /// <summary>
        /// 部门
        /// </summary>
        private readonly RB_DepartmentRepository departmentRepository = new RB_DepartmentRepository();
        /// <summary>
        /// 账号列表
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();
        /// <summary>
        /// 素材
        /// </summary>
        private readonly RB_WeChat_MediumRepository weChat_MediumRepository = new RB_WeChat_MediumRepository();
        /// <summary>
        /// 素材分组
        /// </summary>
        private readonly RB_WeChat_MediumGroupRepository weChat_MediumGroupRepository = new RB_WeChat_MediumGroupRepository();
        /// <summary>
        /// 欢迎语
        /// </summary>
        private readonly RB_WeChat_WelcomesRepository weChat_WelcomesRepository = new RB_WeChat_WelcomesRepository();
        /// <summary>
        /// 客户标签
        /// </summary>
        private readonly RB_WeChat_LableRepository weChat_LableRepository = new RB_WeChat_LableRepository();
        /// <summary>
        /// 渠道分组
        /// </summary>
        private readonly RB_WeChat_ChannelGroupRepository weChat_ChannelGroupRepository = new RB_WeChat_ChannelGroupRepository();
        /// <summary>
        /// 人员添加上限
        /// </summary>
        private readonly RB_WeChat_ChannelLimitRepository weChat_ChannelLimitRepository = new RB_WeChat_ChannelLimitRepository();
        /// <summary>
        /// 渠道活码
        /// </summary>
        private readonly RB_WeChat_ChannelRepository weChat_ChannelRepository = new RB_WeChat_ChannelRepository();
        /// <summary>
        /// 活码周期
        /// </summary>
        private readonly RB_WeChat_ChannelWeekRepository weChat_ChannelWeekRepository = new RB_WeChat_ChannelWeekRepository();
        /// <summary>
        /// 周期欢迎语
        /// </summary>
        private readonly RB_WeChat_ChannelWelcomeRepository weChat_ChannelWelcomeRepository = new RB_WeChat_ChannelWelcomeRepository();
        /// <summary>
        /// 添加客户记录
        /// </summary>
        private readonly RB_WeChat_ChannelRecordRepository weChat_ChannelRecordRepository = new RB_WeChat_ChannelRecordRepository();
        /// <summary>
        /// 渠道码日志
        /// </summary>
        private readonly RB_WeChat_ChannelLogRepository weChat_ChannelLogRepository = new RB_WeChat_ChannelLogRepository();

        

        #region 微信配置
        /// <summary>
        /// 获取企业微信配置
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public WorkChatConfig GetWeChatConfigModel(RB_WeChat_Config_ViewModel model)
        {
            //var dmodel = weChat_ConfigRepository.GetList(model).FirstOrDefault();
            //if (dmodel == null) { dmodel = new RB_WeChat_Config_ViewModel(); }
            return WeChatReidsCache.GetWorkChatConfig(model.Group_Id);
        }

        /// <summary>
        /// 新增/修改企业微信配置
        /// </summary>
        /// <param name="demdoel"></param>
        /// <returns></returns>
        public string SetWeChatConfig(RB_WeChat_Config_ViewModel demdoel)
        {
            if (demdoel.Enable == 1)
            {
                #region 通讯录
                var TelToken = QYWeiXinHelper.GetToken(demdoel.WX_CorpId, demdoel.Employee_Secret);
                if (TelToken.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                {
                    WeChatReidsCache.TokenSet(Cache.CacheKey.QYWeChat_TelToken_Key + demdoel.Group_Id, TelToken.access_token, TelToken.expires_in - 1);
                }
                else
                {
                    return "token请求失败";
                }
                #endregion
                #region 外部人员
                var EmpToken = QYWeiXinHelper.GetToken(demdoel.WX_CorpId, demdoel.Contact_Secret);
                if (EmpToken.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                {
                    WeChatReidsCache.TokenSet(Cache.CacheKey.QYWeChat_EmpToken_Key + demdoel.Group_Id, EmpToken.access_token, EmpToken.expires_in - 1);
                }
                else
                {
                    return "token请求失败";
                }
                #endregion
            }

            if (demdoel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_Config_ViewModel.Name),demdoel.Name},
                    { nameof(RB_WeChat_Config_ViewModel.WX_CorpId),demdoel.WX_CorpId},
                    { nameof(RB_WeChat_Config_ViewModel.Employee_Secret),demdoel.Employee_Secret},
                    { nameof(RB_WeChat_Config_ViewModel.Contact_Secret),demdoel.Contact_Secret},
                    { nameof(RB_WeChat_Config_ViewModel.TelEvent_CallBack),demdoel.TelEvent_CallBack},
                    { nameof(RB_WeChat_Config_ViewModel.EmpEvent_CallBack),demdoel.EmpEvent_CallBack},
                    { nameof(RB_WeChat_Config_ViewModel.Token),demdoel.Token},
                    { nameof(RB_WeChat_Config_ViewModel.Encoding_Aes_Key),demdoel.Encoding_Aes_Key},
                    { nameof(RB_WeChat_Config_ViewModel.Enable),demdoel.Enable},
                    { nameof(RB_WeChat_Config_ViewModel.UpdateBy),demdoel.UpdateBy},
                    { nameof(RB_WeChat_Config_ViewModel.UpdateTime),demdoel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_WeChat_Config_ViewModel.Id),
                          FiledValue=demdoel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = false;
                if (weChat_ConfigRepository.Update(keyValues, wheres)) 
                {
                    flag = true;
                    //更新缓存
                    WeChatReidsCache.UpdateConfig(demdoel.Id);
                }
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                var id = weChat_ConfigRepository.Insert(demdoel);
                bool flag = false;
                if (id > 0) 
                {
                    flag = true;
                    //更新缓存
                    WeChatReidsCache.UpdateConfig(id);
                }
                return flag ? "" : "出错了，请联系管理员";
            }
        }

        #endregion

        #region 同步部门人员
        /// <summary>
        /// 同步部门
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetSyncEduDepartment(UserInfo userInfo)
        {
            var configmodel = weChat_ConfigRepository.GetList(new RB_WeChat_Config_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 }).FirstOrDefault();
            if (configmodel == null || configmodel.Enable != 1) { return "未启用企业微信，无法同步"; }
            string token = GetEmployeeToken(userInfo.Group_Id, configmodel);
            if (string.IsNullOrEmpty(token)) { return "token获取失败"; }

            //获取教育部门列表
            var dlist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = userInfo.Group_Id });

            //树形结构遍历
            var firstList = dlist.Where(x => x.ParentId == 0).ToList();
            foreach (var item in firstList) {
                if (item.WorkDepartId <= 0)
                {
                    //需在微信端创建
                    var CDModle = QYWeiXinHelper.CreateDepartment(token, item.DeptName, 1, item.DeptSort);
                    if (CDModle.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                    {
                        item.WorkDepartId = Convert.ToInt32(CDModle.id);
                        //更新原部门微信部门Id绑定
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Department_ViewModel.WorkDepartId),item.WorkDepartId}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Department_ViewModel.DeptId),
                                  FiledValue=item.DeptId,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        departmentRepository.Update(keyValues, wheres);
                    }
                    else {
                        LogHelper.Write("企业微信部门创建失败DeptId：" + item.DeptId + "  消息：" + CDModle.errmsg);
                        return "出问题咯";
                    }
                }
                //开始遍历下级
                SyncEduDepartmentChildList(item.DeptId, item.WorkDepartId, dlist, token);
            }
            LogHelper.WriteInfo("用户" + userInfo.AccountName + "(" + userInfo.Id + ") 操作同步部门至企业微信");
            return "";
        }

        /// <summary>
        /// 递归处理下级
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="dlist"></param>
        public void SyncEduDepartmentChildList(int parentId, int parentWorkDepartId, List<RB_Department_ViewModel> dlist, string token) {
            var childList = dlist.Where(x => x.ParentId == parentId).ToList();
            foreach (var item in childList) {
                if (item.WorkDepartId <= 0)
                {
                    //需在微信端创建
                    var CDModle = QYWeiXinHelper.CreateDepartment(token, item.DeptName, parentWorkDepartId, item.DeptSort);
                    if (CDModle.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                    {
                        item.WorkDepartId = Convert.ToInt32(CDModle.id);
                        //更新原部门微信部门Id绑定
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Department_ViewModel.WorkDepartId),item.WorkDepartId}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Department_ViewModel.DeptId),
                                  FiledValue=item.DeptId,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        departmentRepository.Update(keyValues, wheres);
                    }
                    else
                    {
                        LogHelper.Write("企业微信部门创建失败DeptId：" + item.DeptId + "  消息：" + CDModle.errmsg);
                        return;
                    }
                }
                //开始遍历下级
                SyncEduDepartmentChildList(item.DeptId, item.WorkDepartId, dlist, token);
            }
        }

        /// <summary>
        /// 同步人员
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetSynvEduEmployee(UserInfo userInfo)
        {
            var configmodel = weChat_ConfigRepository.GetList(new RB_WeChat_Config_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 }).FirstOrDefault();
            if (configmodel == null || configmodel.Enable != 1) { return "未启用企业微信，无法同步"; }
            string token = GetEmployeeToken(userInfo.Group_Id, configmodel);
            if (string.IsNullOrEmpty(token)) { return "token获取失败"; }

            //获取企业微信端所有的部门人员
            var WeiXinEmpList = QYWeiXinHelper.GetDepartmentMemberInfo(token, 1, 1);
            if (WeiXinEmpList.errcode != Senparc.Weixin.ReturnCode_Work.请求成功) {
                LogHelper.Write("获取企业微信部门下人员失败：" + WeiXinEmpList.errmsg);
                return "获取企业微信部门下人员失败"; 
            }
            var wxEmpList = WeiXinEmpList.userlist;

            //获取所有的部门
            var dlist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = userInfo.Group_Id });
            //获取所有的人员
            var elist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, IsLeave = 1 });//.Take(10);//;;;;;;;;;;;;;;注意
            foreach (var item in elist.Where(x=> string.IsNullOrEmpty(x.WorkUserId))) {
                var dmodel = dlist.Where(x => x.DeptId == item.Dept_Id).FirstOrDefault();
                int wxDeptId = dmodel?.WorkDepartId ?? 1;
                string WorkUserId = "";
                //根据手机号码  强验证
                var wxModel = wxEmpList.Where(x => x.mobile == item.Account).FirstOrDefault();
                if (wxModel == null)
                {
                    //成员UserID。对应管理端的帐号，企业内必须唯一。不区分大小写，长度为1~64个字节。只能由数字、字母和“_-@.”四种字符组成，且第一个字符必须是数字或字母。
                    string userId = item.Id + "_" + DateTime.Now.ToString("yyyyMMddHHmmssffff@") + (new Random().Next(1000, 9999));//规则生成
                    //新增用户
                    var inserMember = new Senparc.Weixin.Work.AdvancedAPIs.MailList.Member.MemberCreateRequest()
                    {
                        to_invite = true,
                        alias = "",
                        userid = userId,
                        name = item.EmployeeName,
                        english_name = "",
                        mobile = item.Account,
                        department = new long[] { wxDeptId },
                        order = new long[] { 0 },
                        position = item.PostName,
                        gender = (item.Sex + 1).ToString(),
                        email = "",
                        enable = 1,
                        avatar_mediaid = "",
                        telephone = "",
                        address = "",
                    };
                    var cmodel = QYWeiXinHelper.CreateMember(token, inserMember);
                    if (cmodel.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                    {
                        WorkUserId = userId;
                    }
                    else {
                        LogHelper.Write("员工 " + item.EmployeeName + "(" + item.Id + ") 创建失败；" + cmodel.errmsg);
                        return "员工 " + item.EmployeeName + "(" + item.Id + ") 创建失败；" + cmodel.errmsg;
                    }
                }
                else {
                    //修改用户
                    WorkUserId = wxModel.userid;
                    //string new_userId = item.Id + "_" + DateTime.Now.ToString("yyyyMMddHHmmssffff@") + (new Random().Next(1000, 9999));//规则生成
                    //执行更新用户名称  设置新的userId   （微信自动生成的userId 只能修改一次用户信息）
                    var updateMember = new Senparc.Weixin.Work.AdvancedAPIs.MailList.Member.MemberUpdateRequest()
                    {
                        new_userid="",
                        alias = "",
                        userid = wxModel.userid,
                        name = item.EmployeeName,
                        english_name = wxModel.english_name,
                        mobile = wxModel.mobile,
                        department = new long[] { wxDeptId },
                        order = new long[] { 0 },
                        position = item.PostName,
                        gender = (item.Sex + 1).ToString(),
                        email = wxModel.email,
                        enable = 1,
                        avatar_mediaid = wxModel.avatar,
                        telephone = "",
                        address = "",
                    };
                    var upmodel = QYWeiXinHelper.UpdateMember(token, updateMember);
                    if (upmodel.errcode != Senparc.Weixin.ReturnCode_Work.请求成功) {
                        LogHelper.Write("员工 " + item.EmployeeName + "(" + item.Id + ") 更新失败；" + upmodel.errmsg);
                        return "员工 " + item.EmployeeName + "(" + item.Id + ") 更新失败；" + upmodel.errmsg;
                    }
                }

                //更新用户表 企业微信用户id
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Account_ViewModel.WorkUserId),WorkUserId}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Account_ViewModel.Id),
                          FiledValue=item.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                accountRepository.Update(keyValues, wheres);
            }
            LogHelper.WriteInfo("用户" + userInfo.AccountName + "(" + userInfo.Id + ") 操作同步人员至企业微信");
            return "";
        }

        /// <summary>
        /// 获取通讯录token
        /// </summary>
        /// <param name="Group_Id"></param>
        /// <param name="configmodel"></param>
        /// <returns></returns>
        private string GetEmployeeToken(int Group_Id, RB_WeChat_Config_ViewModel configmodel)
        {
            string token = WeChatReidsCache.GetToken(Cache.CacheKey.QYWeChat_TelToken_Key + Group_Id);
            if (string.IsNullOrEmpty(token))
            {
                var TelToken = QYWeiXinHelper.GetToken(configmodel.WX_CorpId, configmodel.Employee_Secret);
                if (TelToken.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                {
                    WeChatReidsCache.TokenSet(Cache.CacheKey.QYWeChat_TelToken_Key + Group_Id, TelToken.access_token, TelToken.expires_in - 1);
                    token = TelToken.access_token;
                }
                else
                {
                    LogHelper.Write("token获取失败 GetEmployeeToken");
                    return "";
                }
            }
            return token;
        }

        #endregion

        #region 用户客户

        /// <summary>
        /// 转移客户
        /// </summary>
        /// <param name="transferUserId"></param>
        /// <param name="receiveUserId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetUserCoustomerTransfer(int transferUserId, int receiveUserId, int customerTransfer, int channelTransfer, UserInfo userInfo)
        {
            var configmodel = weChat_ConfigRepository.GetList(new RB_WeChat_Config_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 }).FirstOrDefault();
            if (configmodel == null || configmodel.Enable != 1) { return "未启用企业微信，无法同步"; }
            string token = GetContactToken(userInfo.Group_Id, configmodel);
            if (string.IsNullOrEmpty(token)) { return "token获取失败"; }

            var transferModel = accountRepository.GetEmployeeInfo(transferUserId);
            var receiveModel = accountRepository.GetEmployeeInfo(receiveUserId);
            if (transferModel == null || receiveModel == null) { return "用户不存在"; }
            if (string.IsNullOrEmpty(transferModel.WorkUserId) || string.IsNullOrEmpty(receiveModel.WorkUserId)) { return "关联企业微信Id不存在，请核实用户后再试"; }

            string msg = "";
            if (customerTransfer == 1)
            {
                List<string> CoustomerList = new List<string>();
                try
                {
                    var excontact = QYWeiXinHelper.GetExternalContactList(token, transferModel.WorkUserId);
                    if (excontact.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                    {
                        if (excontact.external_userid != null && excontact.external_userid.Any())
                        {
                            CoustomerList = excontact.external_userid;
                        }
                    }
                    else
                    {
                        return "企业微信获取客户列表失败";
                    }
                }
                catch (Exception ex)
                {
                    if (!ex.Message.Contains("84061"))
                    {
                        return "当前用户不存在外部联系人的关系";
                    }
                }
                if (CoustomerList.Any())
                {
                    int pageIndex = (int)Math.Ceiling(Convert.ToDecimal(CoustomerList.Count()) / 100);
                    int pageSize = 100;//微信只支持单次100条数据
                    bool uflag = false;
                    for (int index = 1; index <= pageIndex; index++)
                    {
                        //开始转移
                        var clist = CoustomerList.Skip((index - 1) * pageSize).Take(pageSize).ToList();
                        if (clist.Any())
                        {
                            string Robj = QYWeiXinHelper.TransferCostomer(token, clist, transferModel.WorkUserId, receiveModel.WorkUserId);
                            if (!string.IsNullOrEmpty(Robj))
                            {
                                JObject parms = JObject.Parse(Robj);
                                int errcode = parms.GetInt("errcode", -1);
                                if (errcode == 0)
                                {
                                    uflag = true;
                                }
                                else
                                {
                                    //失败
                                    return "转移客户失败，请联系管理员后再试";
                                }
                            }
                            else
                            {
                                return "请求失败，请联系管理员";
                            }
                        }
                    }
                    if (uflag)
                    {
                        //成功
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_Account_ViewModel.IsWorkTransfer),1 }
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                    FiledName=nameof(RB_Account_ViewModel.Id),
                                    FiledValue=transferModel.Id,
                                    OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        bool flag = accountRepository.Update(keyValues, wheres);
                        msg = flag ? "" : "出错了，请联系管理员";
                    }
                }
            }

            #region 转移渠道码配置用户
            if (channelTransfer == 1)
            {
                msg += TransferChannelUser(transferUserId, receiveUserId, userInfo);
            }
            #endregion
            LogHelper.WriteInfo("用户" + userInfo.AccountName + "(" + userInfo.Id + ") 操作在职客户转移，由" + transferUserId + "=>" + receiveUserId);
            return msg;
        }

        /// <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>
        /// 定时器中获取外部联系人token
        /// </summary>
        /// <param name="Group_Id"></param>
        /// <param name="configmodel"></param>
        /// <returns></returns>
        private string GetContactTokenForTimer(int Group_Id, RB_WeChat_Config_ViewModel configmodel) {
            string token = WeChatReidsCache.GetToken(Cache.CacheKey.QYWeChat_EmpToken_Key + Group_Id);
            if (string.IsNullOrEmpty(token))
            {
                token = GetTokenForServer(configmodel.WX_CorpId, configmodel.Contact_Secret, out int expires_in);
                if (string.IsNullOrEmpty(token))
                {
                    LogHelper.Write("token获取失败 GetTokenForServer");
                    return "";
                }
                WeChatReidsCache.TokenSet(Cache.CacheKey.QYWeChat_EmpToken_Key + Group_Id, token, expires_in - 1);
            }
            return token;
        }

        /// <summary>
        /// 获取离职员工客户列表
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetLeaveUserClientList(UserInfo userInfo)
        {
            var configmodel = weChat_ConfigRepository.GetList(new RB_WeChat_Config_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 }).FirstOrDefault();
            if (configmodel == null || configmodel.Enable != 1) { return "未启用企业微信，无法同步"; }
            string token = GetContactToken(userInfo.Group_Id, configmodel);
            if (string.IsNullOrEmpty(token)) { return "token获取失败"; }

            List<EmpClientModel> list = new List<EmpClientModel>();
            for (int i = 0; i < 50; i++)
            {
                var rmsg = QYWeiXinHelper.GetUnassignedList(token, i);
                if (rmsg.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                {
                    list.AddRange(rmsg.info);
                    if (rmsg.is_last)
                    {
                        break;
                    }
                }
                else {
                    LogHelper.Write("获取离职员工客户列表失败：" + rmsg.errmsg);
                    break;
                }
            }

            #region 分组查询员工信息
            List<object> RList = new List<object>();
            if (list.Any())
            {
                string EmpWorkUserId = "'" + string.Join("','", list.Select(x => x.handover_userid).Distinct()) + "'";
                var empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, WorkUserIds = EmpWorkUserId });
                foreach (var userId in list.Select(x => x.handover_userid).Distinct()) {
                    var clientList = list.Where(x => x.handover_userid == userId).ToList();
                    var empModel = empList.Where(x => x.WorkUserId == userId).FirstOrDefault();
                    RList.Add(new
                    {
                        WorkUserId = userId,
                        EmpId = empModel?.Id ?? 0,
                        EmpName = empModel?.EmployeeName ?? "",
                        DeptName = empModel?.DeptName ?? "",
                        ClientNum = clientList.Count(),
                        ClientList = clientList
                    });
                }
            }
            #endregion
            return RList;
        }

        /// <summary>
        /// 离职人员客户转移
        /// </summary>
        /// <param name="transferUserId"></param>
        /// <param name="receiveUserId"></param>
        /// <param name="clientList"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetLeaveUserCustomerTransfer(int transferUserId, int receiveUserId, string clientList, UserInfo userInfo)
        {
            List<EmpClientModel> clilist = JsonHelper.DeserializeObject<List<EmpClientModel>>(clientList);
            if (!clilist.Any()) { return "客户列表不能为空"; }

            var configmodel = weChat_ConfigRepository.GetList(new RB_WeChat_Config_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 }).FirstOrDefault();
            if (configmodel == null || configmodel.Enable != 1) { return "未启用企业微信，无法同步"; }
            string token = GetContactToken(userInfo.Group_Id, configmodel);
            if (string.IsNullOrEmpty(token)) { return "token获取失败"; }

            var transferModel = accountRepository.GetEmployeeInfo(transferUserId);
            var receiveModel = accountRepository.GetEmployeeInfo(receiveUserId);
            if (transferModel == null || receiveModel == null) { return "用户不存在"; }
            if (string.IsNullOrEmpty(transferModel.WorkUserId) || string.IsNullOrEmpty(receiveModel.WorkUserId)) { return "关联企业微信Id不存在，请核实用户后再试"; }

            var CoustomerList = clilist.Select(x => x.external_userid).ToList();
            int pageIndex = (int)Math.Ceiling(Convert.ToDecimal(CoustomerList.Count()) / 100);
            int pageSize = 100;//微信只支持单次100条数据
            for (int index = 1; index <= pageIndex; index++)
            {
                //开始转移
                var clist = CoustomerList.Skip((index - 1) * pageSize).Take(pageSize).ToList();
                if (clist.Any())
                {
                    var requestL = new TransferCustomerRequest()
                    {
                        handover_userid = transferModel.WorkUserId,
                        takeover_userid = receiveModel.WorkUserId,
                        external_userid = clist
                    };
                    var Rmsg = QYWeiXinHelper.LeaveTransferCustomer(token, requestL);
                    if (Rmsg.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                    {
                        LogHelper.Write("离职转移客户失败：" + Rmsg.errmsg);
                        return "转移客户失败，请联系管理员后再试";
                    }
                }
            }

            LogHelper.WriteInfo("用户" + userInfo.AccountName + "(" + userInfo.Id + ") 操作离职人员客户转移，由" + transferUserId + "=>" + receiveUserId);
            return "";
        }

        #endregion

        #region 素材管理
        /// <summary>
        /// 获取素材分组分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_MediumGroup_ViewModel> GetWeChatMediumGroupPageList(int pageIndex, int pageSize, out long count, RB_WeChat_MediumGroup_ViewModel demodel)
        {
            return weChat_MediumGroupRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取素材分组列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_MediumGroup_ViewModel> GetWeChatMediumGroupList(RB_WeChat_MediumGroup_ViewModel demodel)
        {
            return weChat_MediumGroupRepository.GetList(demodel);
        }

        /// <summary>
        /// 新增修改素材分组
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetWeChatMediumGroup(RB_WeChat_MediumGroup_ViewModel demodel)
        {
            bool flag;
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_MediumGroup_ViewModel.Name),demodel.Name},
                    { nameof(RB_WeChat_MediumGroup_ViewModel.Sort),demodel.Sort},
                    { nameof(RB_WeChat_MediumGroup_ViewModel.UpdateBy),demodel.UpdateBy},
                    { nameof(RB_WeChat_MediumGroup_ViewModel.UpdateTime),demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_WeChat_MediumGroup_ViewModel.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                flag = weChat_MediumGroupRepository.Update(keyValues, wheres);
            }
            else {
                flag = weChat_MediumGroupRepository.Insert(demodel) >0;                
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 删除分组
        /// </summary>
        /// <param name="mediumId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelWeChatMediumGroup(int mediumId, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_WeChat_MediumGroup_ViewModel.Status),1},
                { nameof(RB_WeChat_MediumGroup_ViewModel.UpdateBy),userInfo.Id},
                { nameof(RB_WeChat_MediumGroup_ViewModel.UpdateTime),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_WeChat_MediumGroup_ViewModel.Id),
                        FiledValue=mediumId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            var flag = weChat_MediumGroupRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }


        /// <summary>
        /// 获取素材分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_Medium_ViewModel> GetWeChatMediumPageList(int pageIndex, int pageSize, out long count, RB_WeChat_Medium_ViewModel demodel)
        {
            var list = weChat_MediumRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                string groupIds = string.Join(",", list.Select(x => x.MediaGroupId).Distinct());
                //查询分组
                var glist = weChat_MediumGroupRepository.GetList(new RB_WeChat_MediumGroup_ViewModel() { Group_Id = demodel.Group_Id, MediumGroupIds = groupIds });
                foreach (var item in list) {
                    item.MediumGroupName = glist.Where(x => x.Id == item.MediaGroupId).FirstOrDefault()?.Name ?? "";

                    switch (item.Type) {
                        case Common.Enum.WeChat.MediumTypeEnum.Text:
                            item.TextModel = JsonHelper.DeserializeObject<MediumTextModel>(item.Content);
                            break;
                        case Common.Enum.WeChat.MediumTypeEnum.Image:
                            item.ImageModel = JsonHelper.DeserializeObject<MediumImageModel>(item.Content);
                            break;
                        case Common.Enum.WeChat.MediumTypeEnum.ImgText:
                            item.ImgTextModel = JsonHelper.DeserializeObject<MediumImgTextModel>(item.Content);
                            break;
                        case Common.Enum.WeChat.MediumTypeEnum.Audio:
                            item.AudioModel = JsonHelper.DeserializeObject<MediumAudioModel>(item.Content);
                            break;
                        case Common.Enum.WeChat.MediumTypeEnum.Video:
                            item.VideoModel = JsonHelper.DeserializeObject<MediumVideoModel>(item.Content);
                            break;
                        case Common.Enum.WeChat.MediumTypeEnum.Applet:
                            item.AppletModel = JsonHelper.DeserializeObject<MediumAppletModel>(item.Content);
                            break;
                        case Common.Enum.WeChat.MediumTypeEnum.File:
                            item.FileModel = JsonHelper.DeserializeObject<MediumFileModel>(item.Content);
                            break;
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 新增/修改素材
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetWeChatMediumInfo(RB_WeChat_Medium_ViewModel demodel, out int mediumId)
        {
            if (demodel.Id > 0)
            {
                mediumId = demodel.Id;
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_Medium_ViewModel.MediaGroupId),demodel.MediaGroupId},
                    { nameof(RB_WeChat_Medium_ViewModel.Is_Sync),demodel.Is_Sync},
                    { nameof(RB_WeChat_Medium_ViewModel.Content),demodel.Content},
                    { nameof(RB_WeChat_Medium_ViewModel.UpdateBy),demodel.UpdateBy},
                    { nameof(RB_WeChat_Medium_ViewModel.UpdateTime),demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_WeChat_Medium_ViewModel.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = weChat_MediumRepository.Update(keyValues, wheres);
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                demodel.Media_Id = "";
                int Id = weChat_MediumRepository.Insert(demodel);
                mediumId = Id;
                return Id > 0 ? "" : "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 转移素材
        /// </summary>
        /// <param name="mediumIdList"></param>
        /// <param name="mediumGroupId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetWecharMediumMore(List<int> mediumIdList, int mediumGroupId, UserInfo userInfo)
        {
            foreach (var mid in mediumIdList) {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_Medium_ViewModel.MediaGroupId),mediumGroupId},
                    { nameof(RB_WeChat_Medium_ViewModel.UpdateBy),userInfo.Id},
                    { nameof(RB_WeChat_Medium_ViewModel.UpdateTime),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_WeChat_Medium_ViewModel.Id),
                          FiledValue=mid,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = weChat_MediumRepository.Update(keyValues, wheres);
                if (flag == false) { return "出错了，请联系管理员"; }
            }
            return "";
        }

        /// <summary>
        /// 删除素材
        /// </summary>
        /// <param name="mediumIdList"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelWecharMediumMore(List<int> mediumIdList, UserInfo userInfo)
        {
            foreach (var mid in mediumIdList)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_Medium_ViewModel.Status),1},
                    { nameof(RB_WeChat_Medium_ViewModel.UpdateBy),userInfo.Id},
                    { nameof(RB_WeChat_Medium_ViewModel.UpdateTime),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_WeChat_Medium_ViewModel.Id),
                          FiledValue=mid,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = weChat_MediumRepository.Update(keyValues, wheres);
                if (flag == false) { return "出错了，请联系管理员"; }
            }
            return "";
        }
        #endregion

        #region 上传素材

        /// <summary>
        /// 上传素材至企业微信
        /// </summary>
        /// <returns></returns>
        public string MediumUpload(int GroupId) {
            var configmodel = weChat_ConfigRepository.GetList(new RB_WeChat_Config_ViewModel() { Group_Id = GroupId, Enable = 1 }).FirstOrDefault();
            if (configmodel == null || configmodel.Enable != 1) { return "未启用企业微信，无法上传"; }

            //获取所有可上传的素材列表
            DateTime dtNow = DateTime.Now;//表示这个时间点启动更新
            var list = weChat_MediumRepository.GetAllCanUploadList(GroupId);
            if (list.Any())
            {
                string token = WeChatReidsCache.GetToken(Cache.CacheKey.QYWeChat_TelToken_Key + GroupId);
                if (string.IsNullOrEmpty(token))
                {
                    token = GetTokenForServer(configmodel.WX_CorpId, configmodel.Employee_Secret, out int expires_in);
                    if (string.IsNullOrEmpty(token)) {
                        LogHelper.Write("token获取失败 GetTokenForServer");
                        return "";
                    }
                    WeChatReidsCache.TokenSet(Cache.CacheKey.QYWeChat_TelToken_Key + GroupId, token, expires_in - 1);
                }

                foreach (var item in list)
                {
                    if (!string.IsNullOrEmpty(item.Content))
                    {
                        LogHelper.Write("Id:" + item.Id);
                        try
                        {
                            string FileName = "", Path = "";
                            Senparc.Weixin.Work.UploadMediaFileType fileType = Senparc.Weixin.Work.UploadMediaFileType.image;
                            if (item.Type == Common.Enum.WeChat.MediumTypeEnum.Image)
                            {
                                //图片
                                var imageModel = JsonHelper.DeserializeObject<MediumImageModel>(item.Content);
                                FileName = imageModel.ImageName;
                                Path = imageModel.ImagePath;
                                fileType = Senparc.Weixin.Work.UploadMediaFileType.image;
                            }
                            else if (item.Type == Common.Enum.WeChat.MediumTypeEnum.Applet)
                            {
                                //小程序图片
                                var appletModel = JsonHelper.DeserializeObject<MediumAppletModel>(item.Content);
                                FileName = appletModel.ImageName;
                                Path = appletModel.ImagePath;
                                fileType = Senparc.Weixin.Work.UploadMediaFileType.image;
                            }
                            else if (item.Type == Common.Enum.WeChat.MediumTypeEnum.Audio)
                            {
                                //音频文件
                                var audioModel = JsonHelper.DeserializeObject<MediumAudioModel>(item.Content);
                                FileName = audioModel.AudioName;
                                Path = audioModel.AudioPath;
                                fileType = Senparc.Weixin.Work.UploadMediaFileType.voice;
                            }
                            else if (item.Type == Common.Enum.WeChat.MediumTypeEnum.Video)
                            {
                                //视频文件
                                var videoModel = JsonHelper.DeserializeObject<MediumVideoModel>(item.Content);
                                FileName = videoModel.VideoName;
                                Path = videoModel.VideoPath;
                                fileType = Senparc.Weixin.Work.UploadMediaFileType.video;
                            }
                            else if (item.Type == Common.Enum.WeChat.MediumTypeEnum.File)
                            {
                                var fileModel = JsonHelper.DeserializeObject<MediumFileModel>(item.Content);
                                FileName = fileModel.FileName;
                                Path = fileModel.FilePath;
                                fileType = Senparc.Weixin.Work.UploadMediaFileType.file;
                            }
                            else {
                                continue;
                            }


                            string filePath = QYWeiXinHelper.CopyFileByUrl(Path, FileName);
                            if (!string.IsNullOrEmpty(filePath))
                            {
                                string RObj = QYWeiXinHelper.UploadMultimedia(token, filePath, fileType);
                                JObject parms = JObject.Parse(RObj);
                                int errcode = parms.GetInt("errcode", -1);//获取状态码 0成功
                                if (errcode == 0)
                                {
                                    //成功
                                    string media_id = parms.GetStringValue("media_id");
                                    //更新素材id
                                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                        { nameof(RB_WeChat_Medium_ViewModel.Media_Id),media_id},
                                        { nameof(RB_WeChat_Medium_ViewModel.LastUploadTime),dtNow},//不然每个更新都会有耗时 导致下次不会更新
                                    };
                                    List<WhereHelper> wheres = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName=nameof(RB_WeChat_Medium_ViewModel.Id),
                                              FiledValue=item.Id,
                                               OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    weChat_MediumRepository.Update(keyValues, wheres);
                                }
                                else {
                                    LogHelper.Write(RObj + "   mediumId：" + item.Id);
                                }
                                File.Delete(filePath);//删除临时文件
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write(ex, "MediumUpload");
                        }
                    }
                }
            }

            return "";
        }

        /// <summary>
        /// 定时器获取token
        /// </summary>
        /// <param name="corpId"></param>
        /// <param name="corpSecret"></param>
        /// <param name="expires_in"></param>
        /// <returns></returns>
        public string GetTokenForServer(string corpId, string corpSecret, out int expires_in)
        {
            expires_in = 0;
            string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + corpSecret;
            string Rmsg = HttpHelper.HttpGet(url);
            if (!string.IsNullOrEmpty(Rmsg))
            {
                JObject parms = JObject.Parse(Rmsg);
                int errcode = parms.GetInt("errcode", -1);
                if (errcode == 0)
                {
                    string token = parms.GetStringValue("access_token");
                    expires_in = parms.GetInt("expires_in", 0);
                    return token;
                }
            }
            LogHelper.Write("token获取失败：" + Rmsg);
            return "";
        }
        #endregion

        #region 欢迎语管理

        /// <summary>
        /// 获取欢迎语分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_Welcomes_ViewModel> GetWeChatWelcomesPageList(int pageIndex, int pageSize, out long count, RB_WeChat_Welcomes_ViewModel demodel)
        {
            var list = weChat_WelcomesRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                var otherList = list.Where(x => x.Type > 1 && !string.IsNullOrEmpty(x.MediumIds)).ToList();
                if (otherList.Any()) {
                    string mediumIds = string.Join(",", otherList.Select(x => x.MediumIds).Distinct());
                    var mlist = weChat_MediumRepository.GetList(new RB_WeChat_Medium_ViewModel() { Group_Id = demodel.Group_Id, MediumIds = mediumIds });
                    foreach (var item in mlist)
                    {
                        switch (item.Type)
                        {
                            case Common.Enum.WeChat.MediumTypeEnum.Text:
                                item.TextModel = JsonHelper.DeserializeObject<MediumTextModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.Image:
                                item.ImageModel = JsonHelper.DeserializeObject<MediumImageModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.ImgText:
                                item.ImgTextModel = JsonHelper.DeserializeObject<MediumImgTextModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.Audio:
                                item.AudioModel = JsonHelper.DeserializeObject<MediumAudioModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.Video:
                                item.VideoModel = JsonHelper.DeserializeObject<MediumVideoModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.Applet:
                                item.AppletModel = JsonHelper.DeserializeObject<MediumAppletModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.File:
                                item.FileModel = JsonHelper.DeserializeObject<MediumFileModel>(item.Content);
                                break;
                        }
                    }
                    foreach (var item in otherList) {
                        if (!string.IsNullOrEmpty(item.MediumIds)) {
                            item.MediumList = mlist.Where(x => ("," + item.MediumIds + ",").Contains("," + x.Id + ",")).ToList();
                        }
                    }
                }

                foreach (var item in list) {
                    item.UserIdList = new List<int>();
                    if (!string.IsNullOrEmpty(item.UserIds)) {
                        item.UserIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.UserIds + "]");
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取欢迎语详情
        /// </summary>
        /// <param name="welcomeId"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public RB_WeChat_Welcomes_ViewModel GetWeChatWelcomesInfo(int welcomeId, int groupId)
        {
            var list = weChat_WelcomesRepository.GetList(new RB_WeChat_Welcomes_ViewModel() { Group_Id = groupId, Id = welcomeId });
            if (list.Any())
            {
                var otherList = list.Where(x => x.Type > 1 && !string.IsNullOrEmpty(x.MediumIds)).ToList();
                if (otherList.Any())
                {
                    string mediumIds = string.Join(",", otherList.Select(x => x.MediumIds).Distinct());
                    var mlist = weChat_MediumRepository.GetList(new RB_WeChat_Medium_ViewModel() { Group_Id = groupId, MediumIds = mediumIds });
                    foreach (var item in mlist)
                    {
                        switch (item.Type)
                        {
                            case Common.Enum.WeChat.MediumTypeEnum.Text:
                                item.TextModel = JsonHelper.DeserializeObject<MediumTextModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.Image:
                                item.ImageModel = JsonHelper.DeserializeObject<MediumImageModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.ImgText:
                                item.ImgTextModel = JsonHelper.DeserializeObject<MediumImgTextModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.Audio:
                                item.AudioModel = JsonHelper.DeserializeObject<MediumAudioModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.Video:
                                item.VideoModel = JsonHelper.DeserializeObject<MediumVideoModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.Applet:
                                item.AppletModel = JsonHelper.DeserializeObject<MediumAppletModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.File:
                                item.FileModel = JsonHelper.DeserializeObject<MediumFileModel>(item.Content);
                                break;
                        }
                    }
                    foreach (var item in otherList)
                    {
                        if (!string.IsNullOrEmpty(item.MediumIds))
                        {
                            item.MediumList = mlist.Where(x => ("," + item.MediumIds + ",").Contains("," + x.Id + ",")).ToList();
                        }
                    }
                }

                foreach (var item in list)
                {
                    item.UserIdList = new List<int>();
                    if (!string.IsNullOrEmpty(item.UserIds))
                    {
                        item.UserIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.UserIds + "]");
                    }
                }
            }
            return list.FirstOrDefault();
        }

        /// <summary>
        /// 获取欢迎语列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_Welcomes_ViewModel> GetWeChatWelcomesList(RB_WeChat_Welcomes_ViewModel demodel) {
            var list = weChat_WelcomesRepository.GetList(demodel);
            if (list.Any())
            {
                var otherList = list.Where(x => x.Type > 1).ToList();
                if (otherList.Any())
                {
                    string mediumIds = string.Join(",", otherList.Select(x => x.MediumIds).Distinct());
                    var mlist = weChat_MediumRepository.GetList(new RB_WeChat_Medium_ViewModel() { Group_Id = demodel.Group_Id, MediumIds = mediumIds });
                    foreach (var item in mlist)
                    {
                        switch (item.Type)
                        {
                            case Common.Enum.WeChat.MediumTypeEnum.Text:
                                item.TextModel = JsonHelper.DeserializeObject<MediumTextModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.Image:
                                item.ImageModel = JsonHelper.DeserializeObject<MediumImageModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.ImgText:
                                item.ImgTextModel = JsonHelper.DeserializeObject<MediumImgTextModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.Audio:
                                item.AudioModel = JsonHelper.DeserializeObject<MediumAudioModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.Video:
                                item.VideoModel = JsonHelper.DeserializeObject<MediumVideoModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.Applet:
                                item.AppletModel = JsonHelper.DeserializeObject<MediumAppletModel>(item.Content);
                                break;
                            case Common.Enum.WeChat.MediumTypeEnum.File:
                                item.FileModel = JsonHelper.DeserializeObject<MediumFileModel>(item.Content);
                                break;
                        }
                    }
                    foreach (var item in otherList)
                    {
                        if (!string.IsNullOrEmpty(item.MediumIds))
                        {
                            item.MediumList = mlist.Where(x => ("," + item.MediumIds + ",").Contains("," + x.Id + ",")).ToList();
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 新增修改欢迎语
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetWeChatWelcomesInfo(RB_WeChat_Welcomes_ViewModel demodel)
        {
            #region 验证素材
            if (demodel.Type == 2) {
                var mediumList = weChat_MediumRepository.GetList(new RB_WeChat_Medium_ViewModel() { Group_Id = demodel.Group_Id, MediumIds = demodel.MediumIds });
                if (!mediumList.Any()) { return "素材不存在"; }
                demodel.MediumIds = string.Join(",", mediumList.Select(x => x.Id));
            }
            #endregion
            bool flag;
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    {nameof(RB_WeChat_Welcomes_ViewModel.Content),demodel.Content },
                    {nameof(RB_WeChat_Welcomes_ViewModel.UserIds),demodel.UserIds },
                    {nameof(RB_WeChat_Welcomes_ViewModel.MediumIds),demodel.MediumIds },
                    {nameof(RB_WeChat_Welcomes_ViewModel.Type),demodel.Type },
                    {nameof(RB_WeChat_Welcomes_ViewModel.UpdateBy),demodel.UpdateBy },
                    {nameof(RB_WeChat_Welcomes_ViewModel.UpdateTime),demodel.UpdateTime },
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_WeChat_Welcomes_ViewModel.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                flag = weChat_WelcomesRepository.Update(keyValues, wheres);
            }
            else {
                flag = weChat_WelcomesRepository.Insert(demodel) > 0;
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 删除欢迎语
        /// </summary>
        /// <param name="welcomesId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelWechatWelcomesInfo(int welcomesId, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                {nameof(RB_WeChat_Welcomes_ViewModel.Status),1 },
                {nameof(RB_WeChat_Welcomes_ViewModel.UpdateBy),userInfo.Id },
                {nameof(RB_WeChat_Welcomes_ViewModel.UpdateTime),DateTime.Now },
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_WeChat_Welcomes_ViewModel.Id),
                        FiledValue=welcomesId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            var flag = weChat_WelcomesRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 通过微信用户ID  获取系统用户信息
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public Employee_ViewModel GetUserInfoForWeiXinWorkUserId(int groupId, string WorkUserID)
        {
            return accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = groupId, WorkUserId = WorkUserID }).FirstOrDefault();
        }

        /// <summary>
        /// 发送新客户欢迎语
        /// </summary>
        /// <param name="token"></param>
        /// <param name="tList"></param>
        /// <param name="transferUserId"></param>
        /// <param name="receiveUserId"></param>
        /// <returns></returns>
        public string SendNewCustomerWelcome(string token, string welcome_code, RB_WeChat_Welcomes_ViewModel model)
        {
            string url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/send_welcome_msg?access_token=" + token;
            object RDate = new object();
            if (model.Type == 1)
            {
                //文本
                RDate = new
                {
                    welcome_code,
                    text = new
                    {
                        content = model.Content
                    }
                };
            }
            else if (model.Type == 2)
            {
                var attList = new List<object>();//组装附件
                foreach (var item in model.MediumList)
                {
                    if (item.Type == Common.Enum.WeChat.MediumTypeEnum.Image)
                    {
                        attList.Add(new
                        {
                            msgtype = "image",
                            image = new
                            {
                                media_id = item.Media_Id,
                                pic_url = ""
                            }
                        });
                    }
                    else if (item.Type == Common.Enum.WeChat.MediumTypeEnum.ImgText)
                    {
                        attList.Add(new
                        {
                            msgtype = "link",
                            link = new
                            {
                                title = item.ImgTextModel.Title,
                                picurl = item.ImgTextModel.ImgPath,
                                desc = item.ImgTextModel.Description,
                                url = item.ImgTextModel.ImgLink
                            }
                        });
                    }
                    else if (item.Type == Common.Enum.WeChat.MediumTypeEnum.Applet)
                    {
                        attList.Add(new
                        {
                            msgtype = "miniprogram",
                            miniprogram = new
                            {
                                title = item.AppletModel.Title,
                                pic_media_id = item.Media_Id,
                                appid = item.AppletModel.AppletId,
                                page = item.AppletModel.Page
                            }
                        });
                    }
                    else if (item.Type == Common.Enum.WeChat.MediumTypeEnum.Video) {
                        attList.Add(new
                        {
                            msgtype = "video",
                            video = new
                            {
                                media_id = item.Media_Id
                            }
                        });
                    }
                    else if (item.Type == Common.Enum.WeChat.MediumTypeEnum.File)
                    {
                        attList.Add(new
                        {
                            msgtype = "file",
                            file = new
                            {
                                media_id = item.Media_Id
                            }
                        });
                    }
                }
                //发送参数
                RDate = new
                {
                    welcome_code,
                    text = new
                    {
                        content = model.Content
                    },
                    attachments = attList
                };
            }
            else { return ""; }
            return HttpHelper.HttpPost(url, JsonHelper.Serialize(RDate), "");
        }

        #endregion

        #region 标签管理

        /// <summary>
        /// 获取标签列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_Lable_ViewModel> GetWeChatLableList(RB_WeChat_Lable_ViewModel demodel)
        {
            var list = weChat_LableRepository.GetList(demodel);
            var GroupList = list.Where(x => x.ParentId == 0).OrderByDescending(x => x.Sort).ToList();
            foreach (var item in GroupList) {
                item.ChildList = list.Where(x => x.ParentId == item.Id).OrderByDescending(x => x.Sort).ToList();
            }
            return GroupList;
        }

        /// <summary>
        /// 根据多个ID获取对应的标签信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public List<RB_WeChat_Lable_ViewModel> GetLabelListByIds(string ids)
        {
            return weChat_LableRepository.GetLabelListByIds(ids);
        }

        /// <summary>
        /// 新增修改分组/标签
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetWeChatLable(RB_WeChat_Lable_ViewModel demodel)
        {
            var configmodel = weChat_ConfigRepository.GetList(new RB_WeChat_Config_ViewModel() { Group_Id = demodel.Group_Id, Enable = 1 }).FirstOrDefault();
            if (configmodel == null || configmodel.Enable != 1) { return "未启用企业微信，无法同步"; }
            string token = GetContactToken(demodel.Group_Id, configmodel);
            if (string.IsNullOrEmpty(token)) { return "token获取失败"; }

            if (demodel.Id > 0)
            {
                //修改
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_Lable_ViewModel.Name),demodel.Name},
                    { nameof(RB_WeChat_Lable_ViewModel.Sort),demodel.Sort},
                    { nameof(RB_WeChat_Lable_ViewModel.UpdateBy),demodel.UpdateBy},
                    { nameof(RB_WeChat_Lable_ViewModel.UpdateTime),demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName=nameof(RB_WeChat_Lable_ViewModel.Id),
                            FiledValue=demodel.Id,
                            OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = weChat_LableRepository.Update(keyValues, wheres);
                if (flag) {
                    var oldModel = weChat_LableRepository.GetEntity(demodel.Id);
                    if (!string.IsNullOrEmpty(oldModel.WXLableId)) {
                        System.Threading.Tasks.Task.Run(() =>
                        {
                            var Rmsg = QYWeiXinHelper.UpdateCoustmerLable(token, new TagModel()
                            {
                                id = oldModel.WXLableId,
                                name = demodel.Name,
                                order = demodel.Sort
                            });
                            if (Rmsg != null && Rmsg.errcode == 0)
                            {
                                //更新成功
                            }
                            else
                            {
                                LogHelper.Write("更新客户标签分组失败：" + Rmsg?.errmsg);
                            }
                        });
                    }
                }
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                //新增
                var Id = weChat_LableRepository.Insert(demodel);
                if (Id > 0) {
                    //企业微信新增
                    if (demodel.ParentId == 0)
                    {
                        //新增子标签
                        foreach (var item in demodel.ChildList)
                        {
                            int qId = weChat_LableRepository.Insert(new Model.Entity.WeChat.RB_WeChat_Lable()
                            {
                                Id = 0,
                                CreateBy = demodel.CreateBy,
                                CreateTime = DateTime.Now,
                                Group_Id = demodel.Group_Id,
                                Name = item.Name,
                                ParentId = Id,
                                Sort = item.Sort,
                                Status = 0,
                                UpdateBy = demodel.UpdateBy,
                                UpdateTime = DateTime.Now,
                                WXLableId = ""
                            });
                            item.Id = qId;
                        }

                        //新增微信标签
                        System.Threading.Tasks.Task.Run(() =>
                        {
                            var tag = demodel.ChildList.Select(x => new TagModel()
                            {
                                name = x.Name,
                                order = x.Sort
                            }).ToList();
                            var groupModel = QYWeiXinHelper.AddCoustmerLable(token, new TagGroupModel()
                            {
                                group_name = demodel.Name,
                                order = demodel.Sort,
                                tag = tag
                            });
                            if (groupModel != null && groupModel.errcode == 0)
                            {
                                string WXLableId = groupModel.tag_group.group_id;
                                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_WeChat_Lable_ViewModel.WXLableId),WXLableId}
                            };
                                List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_WeChat_Lable_ViewModel.Id),
                                      FiledValue=Id,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                                bool flag1 = weChat_LableRepository.Update(keyValues, wheres);
                                if (flag1)
                                {
                                    //新增子标签
                                    foreach (var item in demodel.ChildList)
                                    {
                                        var tagModel = groupModel.tag_group.tag.Where(x => x.name == item.Name).FirstOrDefault();
                                        if (tagModel != null)
                                        {
                                            weChat_LableRepository.Insert(new Model.Entity.WeChat.RB_WeChat_Lable()
                                            {
                                                Id = 0,
                                                CreateBy = demodel.CreateBy,
                                                CreateTime = DateTime.Now,
                                                Group_Id = demodel.Group_Id,
                                                Name = tagModel.name,
                                                ParentId = Id,
                                                Sort = tagModel.order,
                                                Status = 0,
                                                UpdateBy = demodel.UpdateBy,
                                                UpdateTime = DateTime.Now,
                                                WXLableId = tagModel.id
                                            });
                                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                            { nameof(RB_WeChat_Lable_ViewModel.WXLableId),WXLableId}
                                        };
                                            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                 FiledName=nameof(RB_WeChat_Lable_ViewModel.Id),
                                                  FiledValue=item.Id,
                                                   OperatorEnum=OperatorEnum.Equal
                                            }
                                        };
                                            weChat_LableRepository.Update(keyValues1, wheres1);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                LogHelper.Write("新增客户标签分组失败：" + groupModel?.errmsg);
                            }
                        });
                    }
                    else {
                        //是标签  先求出其组的内容
                        var pmodel = weChat_LableRepository.GetEntity(demodel.ParentId);
                        if (pmodel != null) {
                            System.Threading.Tasks.Task.Run(() =>
                            {
                                var groupModel = QYWeiXinHelper.AddCoustmerLable(token, new TagGroupModel()
                                {
                                    group_id = pmodel.WXLableId,
                                    tag = new List<TagModel>() {
                                    new TagModel(){
                                         name= demodel.Name,
                                          order=demodel.Sort
                                    }
                                }
                                });
                                if (groupModel != null && groupModel.errcode == 0)
                                {
                                    string WXLableId = groupModel.tag_group.tag.FirstOrDefault()?.id;
                                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                    { nameof(RB_WeChat_Lable_ViewModel.WXLableId),WXLableId}
                                };
                                    List<WhereHelper> wheres = new List<WhereHelper>() {
                                    new WhereHelper(){
                                         FiledName=nameof(RB_WeChat_Lable_ViewModel.Id),
                                          FiledValue=Id,
                                           OperatorEnum=OperatorEnum.Equal
                                    }
                                };
                                    weChat_LableRepository.Update(keyValues, wheres);
                                }
                                else
                                {
                                    LogHelper.Write("新增客户标签分组失败：" + groupModel?.errmsg);
                                }
                            });
                        }
                    }
                }
                return Id > 0 ? "" : "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 删除标签/分组
        /// </summary>
        /// <param name="lableId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelWeChatLable(int lableId, UserInfo userInfo)
        {
            var configmodel = weChat_ConfigRepository.GetList(new RB_WeChat_Config_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 }).FirstOrDefault();
            if (configmodel == null || configmodel.Enable != 1) { return "未启用企业微信，无法同步"; }
            string token = GetContactToken(userInfo.Group_Id, configmodel);
            if (string.IsNullOrEmpty(token)) { return "token获取失败"; }

            var model = weChat_LableRepository.GetEntity(lableId);
            if (model == null) { return "标签不存在"; }

            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_WeChat_Lable_ViewModel.Status),1 },
                { nameof(RB_WeChat_Lable_ViewModel.UpdateBy),userInfo.Id },
                { nameof(RB_WeChat_Lable_ViewModel.UpdateTime),DateTime.Now },
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_WeChat_Lable_ViewModel.Id),
                      FiledValue=lableId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = weChat_LableRepository.Update(keyValues, wheres);
            if (flag) {
                //删除企业微信标签
                List<string> tagIdList = new List<string>();
                List<string> groupIdList = new List<string>();
                if (model.ParentId == 0)
                {
                    //分组
                    groupIdList.Add(model.WXLableId);
                }
                else {
                    //标签
                    tagIdList.Add(model.WXLableId);
                }
                System.Threading.Tasks.Task.Run(() =>
                {
                    var Rmsg = QYWeiXinHelper.DelCoustmerLable(token, tagIdList, groupIdList);
                    if (Rmsg == null || Rmsg.errcode != 0)
                    {
                        LogHelper.Write("删除企业微信标签失败：" + Rmsg.errmsg);
                    }
                });
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 同步企业微信标签
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetSyncWeChatLable(UserInfo userInfo)
        {
            //获取系统现有的标签列表
            var llist = weChat_LableRepository.GetList(new RB_WeChat_Lable_ViewModel() { Group_Id = userInfo.Group_Id });
            if (llist.Any()) { return "系统已存在标签，无法初始化标签"; }

            var configmodel = weChat_ConfigRepository.GetList(new RB_WeChat_Config_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 }).FirstOrDefault();
            if (configmodel == null || configmodel.Enable != 1) { return "未启用企业微信，无法同步"; }
            string token = GetContactToken(userInfo.Group_Id, configmodel);
            if (string.IsNullOrEmpty(token)) { return "token获取失败"; }

            //获取微信标签列表
            var Rmsg = QYWeiXinHelper.GetCustomerLableForQYWeiXin(token);
            if (Rmsg == null || Rmsg.errcode != 0) { return "获取企业微信标签列表失败"; }

            foreach (var item in Rmsg.tag_group) {
                //新增组
                int groupId = weChat_LableRepository.Insert(new Model.Entity.WeChat.RB_WeChat_Lable()
                {
                    Id = 0,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    Group_Id = userInfo.Group_Id,
                    Name = item.group_name,
                    ParentId = 0,
                    Sort = item.order,
                    Status = 0,
                    UpdateBy = userInfo.Id,
                    UpdateTime = DateTime.Now,
                    WXLableId = item.group_id
                });
                if (groupId > 0) {
                    foreach (var qitem in item.tag) {
                        weChat_LableRepository.Insert(new Model.Entity.WeChat.RB_WeChat_Lable()
                        {
                            Id = 0,
                            CreateBy = userInfo.Id,
                            CreateTime = DateTime.Now,
                            Group_Id = userInfo.Group_Id,
                            Name = qitem.name,
                            ParentId = groupId,
                            Sort = qitem.order,
                            Status = 0,
                            UpdateBy = userInfo.Id,
                            UpdateTime = DateTime.Now,
                            WXLableId = qitem.id
                        });
                    }
                }
            }
            return "";
        }
        #endregion

        #region 渠道分组

        /// <summary>
        /// 获取渠道分组分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_ChannelGroup_ViewModel> GetWeChatChannelGroupPageList(int pageIndex, int pageSize, out long count, RB_WeChat_ChannelGroup_ViewModel demodel)
        {
            return weChat_ChannelGroupRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取渠道分组列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_ChannelGroup_ViewModel> GetWeChatChannelGroupList(RB_WeChat_ChannelGroup_ViewModel demodel)
        {
            return weChat_ChannelGroupRepository.GetList(demodel);
        }

        /// <summary>
        /// 新增修改渠道分组
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetWeChatChannelGroup(RB_WeChat_ChannelGroup_ViewModel demodel)
        {
            bool flag;
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_ChannelGroup_ViewModel.Name),demodel.Name},
                    { nameof(RB_WeChat_ChannelGroup_ViewModel.Sort),demodel.Sort},
                    { nameof(RB_WeChat_ChannelGroup_ViewModel.UpdateBy),demodel.UpdateBy},
                    { nameof(RB_WeChat_ChannelGroup_ViewModel.UpdateTime),demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_WeChat_ChannelGroup_ViewModel.Id),
                          FiledValue=demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                flag = weChat_ChannelGroupRepository.Update(keyValues, wheres);
            }
            else
            {
                flag = weChat_ChannelGroupRepository.Insert(demodel) > 0;
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 删除分组
        /// </summary>
        /// <param name="mediumId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelWeChatChannelGroup(int mediumId, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_WeChat_ChannelGroup_ViewModel.Status),1},
                { nameof(RB_WeChat_ChannelGroup_ViewModel.UpdateBy),userInfo.Id},
                { nameof(RB_WeChat_ChannelGroup_ViewModel.UpdateTime),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_WeChat_ChannelGroup_ViewModel.Id),
                        FiledValue=mediumId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            var flag = weChat_ChannelGroupRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        #endregion

        #region 渠道活码

        /// <summary>
        /// 渠道活码
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_Channel_ViewModel> GetWeChatChannelPageList(int pageIndex, int pageSize, out long count, RB_WeChat_Channel_ViewModel demodel)
        {
            var list = weChat_ChannelRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                string groupIds = string.Join(",", list.Select(x => x.ChannelGroupId).Distinct());
                var glist = weChat_ChannelGroupRepository.GetList(new RB_WeChat_ChannelGroup_ViewModel() { Group_Id = demodel.Group_Id, ChannelGroupIds = groupIds });
                string lableIds = string.Join(",", list.Where(x => !string.IsNullOrEmpty(x.LableIds)).Select(x => x.LableIds));
                List<RB_WeChat_Lable_ViewModel> lableList = new List<RB_WeChat_Lable_ViewModel>();
                if (!string.IsNullOrEmpty(lableIds)) {
                    lableList = weChat_LableRepository.GetList(new RB_WeChat_Lable_ViewModel() { Group_Id = demodel.Group_Id, LableIds = lableIds });
                }
                //获取客户数量
                string channelIds = string.Join(",", list.Select(x => x.Id));
                var clist = weChat_ChannelRecordRepository.GetChanncelCustomerNum(demodel.Group_Id, 1, channelIds);
                foreach (var item in list) {
                    item.ChannelGroupName = glist.Where(x => x.Id == item.ChannelGroupId).FirstOrDefault()?.Name ?? "";
                    item.CustomerNum = clist.Where(x => x.ChannelId == item.Id).FirstOrDefault()?.CustomerNum ?? 0;
                    item.LabelList = new List<string>();
                    if (!string.IsNullOrEmpty(item.LableIds)) {
                        List<int> lableIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.LableIds + "]");

                        foreach (var qitem in lableIdList) {
                            item.LabelList.Add(lableList.Where(x => x.Id == qitem).FirstOrDefault()?.Name ?? "");
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取渠道活码详情
        /// </summary>
        /// <param name="channelId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public RB_WeChat_Channel_ViewModel GetWeChatChannelInfo(int channelId, UserInfo userInfo)
        {
            var cmodel = weChat_ChannelRepository.GetEntity<RB_WeChat_Channel_ViewModel>(channelId);
            if (cmodel == null) { return null; }
            //获取标签Id
            cmodel.LabelIdList = new List<int>();
            if (!string.IsNullOrEmpty(cmodel.LableIds)) { 
                cmodel.LabelIdList = JsonHelper.DeserializeObject<List<int>>("["+cmodel.LableIds+"]");
            }

            #region 获取周期
            var weekList = weChat_ChannelWeekRepository.GetList(new RB_WeChat_ChannelWeek_ViewModel() { Group_Id = userInfo.Group_Id, ChannelId = channelId });
            if (weekList.Any()) {
                string empIds = string.Join(",", weekList.Where(x => !string.IsNullOrEmpty(x.EmpIds)).Select(x => x.EmpIds));
                string deptIds = string.Join(",", weekList.Where(x => !string.IsNullOrEmpty(x.DeptIds)).Select(x => x.DeptIds));
                List<Employee_ViewModel> EmpList = new List<Employee_ViewModel>();
                List<RB_Department_ViewModel> DeptList = new List<RB_Department_ViewModel>();
                if (!string.IsNullOrEmpty(empIds)) {
                    EmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, QIds = empIds, IsLeave = 1 });
                }
                if (!string.IsNullOrEmpty(deptIds)) {
                    DeptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = userInfo.Group_Id, QDeptIds = deptIds });
                }
                foreach (var item in weekList) {
                    item.EmpList = new List<WeekEmpDeptModel>();
                    item.DeptList = new List<WeekEmpDeptModel>();
                    if (!string.IsNullOrEmpty(item.EmpIds)) {
                        List<int> empIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.EmpIds + "]");
                        item.EmpList = EmpList.Where(x => empIdList.Contains(x.Id)).Select(x => new WeekEmpDeptModel()
                        {
                            Id = x.Id,
                            Name = x.EmployeeName
                        }).ToList();
                    }
                    if (!string.IsNullOrEmpty(item.DeptIds)) {
                        List<int> deptIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.DeptIds + "]");
                        item.DeptList = DeptList.Where(x => deptIdList.Contains(x.DeptId)).Select(x => new WeekEmpDeptModel()
                        {
                            Id = x.DeptId,
                            Name = x.DeptName
                        }).ToList();
                    }
                }
            }

            cmodel.WeekList = weekList.Where(x => x.Type == 1).ToList();
            if (cmodel.SpecialDateEnable == 1)
            {
                cmodel.SpecialWeekList = weekList.Where(x => x.Type == 2).ToList();
            }
            #endregion

            #region 人员添加上限
            if (cmodel.EmpAddLimit == 1) {
                cmodel.LimitList = weChat_ChannelLimitRepository.GetList(new RB_WeChat_ChannelLimit_ViewModel() { Group_Id = userInfo.Group_Id, ChannelId = channelId });
                if (cmodel.LimitList.Any()) {
                    string empIds = string.Join(",", cmodel.LimitList.Select(x => x.EmpId));
                    var EmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, QIds = empIds, IsLeave = 1 });
                    foreach (var item in cmodel.LimitList) {
                        item.EmpName = EmpList.Where(x => x.Id == item.EmpId).FirstOrDefault()?.EmployeeName ?? "";
                    }
                }

                if (!string.IsNullOrEmpty(cmodel.EmpBackUp)) {
                    var EmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, QIds = cmodel.EmpBackUp, IsLeave = 1 });
                    cmodel.EmpBackUpList = EmpList.Select(x => new WeekEmpDeptModel()
                    {
                        Id = x.Id,
                        Name = x.EmployeeName
                    }).ToList();
                }
            }
            #endregion

            #region 获取欢迎语
            if (cmodel.WelcomeEnable == 1)
            {
                var welcomeList = weChat_ChannelWelcomeRepository.GetList(new RB_WeChat_ChannelWelcome_ViewModel() { Group_Id = userInfo.Group_Id, ChannelId = channelId });
                if (welcomeList.Any())
                {
                    var otherList = welcomeList.Where(x => !string.IsNullOrEmpty(x.MediumIds)).ToList();
                    if (otherList.Any())
                    {
                        string mediumIds = string.Join(",", otherList.Select(x => x.MediumIds).Distinct());
                        var mlist = weChat_MediumRepository.GetList(new RB_WeChat_Medium_ViewModel() { Group_Id = userInfo.Group_Id, MediumIds = mediumIds });
                        foreach (var item in mlist)
                        {
                            switch (item.Type)
                            {
                                case Common.Enum.WeChat.MediumTypeEnum.Text:
                                    item.TextModel = JsonHelper.DeserializeObject<MediumTextModel>(item.Content);
                                    break;
                                case Common.Enum.WeChat.MediumTypeEnum.Image:
                                    item.ImageModel = JsonHelper.DeserializeObject<MediumImageModel>(item.Content);
                                    break;
                                case Common.Enum.WeChat.MediumTypeEnum.ImgText:
                                    item.ImgTextModel = JsonHelper.DeserializeObject<MediumImgTextModel>(item.Content);
                                    break;
                                case Common.Enum.WeChat.MediumTypeEnum.Audio:
                                    item.AudioModel = JsonHelper.DeserializeObject<MediumAudioModel>(item.Content);
                                    break;
                                case Common.Enum.WeChat.MediumTypeEnum.Video:
                                    item.VideoModel = JsonHelper.DeserializeObject<MediumVideoModel>(item.Content);
                                    break;
                                case Common.Enum.WeChat.MediumTypeEnum.Applet:
                                    item.AppletModel = JsonHelper.DeserializeObject<MediumAppletModel>(item.Content);
                                    break;
                                case Common.Enum.WeChat.MediumTypeEnum.File:
                                    item.FileModel = JsonHelper.DeserializeObject<MediumFileModel>(item.Content);
                                    break;
                            }
                        }
                        foreach (var item in otherList)
                        {
                            if (!string.IsNullOrEmpty(item.MediumIds))
                            {
                                item.MediumList = mlist.Where(x => ("," + item.MediumIds + ",").Contains("," + x.Id + ",")).ToList();
                            }
                        }
                    }
                }

                cmodel.WelcomeList = welcomeList.Where(x => x.Type == 1).ToList();
                if (cmodel.WelcomeWeekEnable == 1)
                {
                    cmodel.WelcomeWeekList = welcomeList.Where(x => x.Type == 2).ToList();
                }
                if (cmodel.WelcomeSpecialEnable == 1)
                {
                    cmodel.WelcomeSpecialList = welcomeList.Where(x => x.Type == 3).ToList();
                }
            }
            #endregion

            return cmodel;
        }

        /// <summary>
        /// 欢迎语回调查询渠道活码
        /// </summary>
        /// <param name="channelId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public RB_WeChat_Channel_ViewModel GetWeChatChannelForBackUp(int channelId)
        {
            var cmodel = weChat_ChannelRepository.GetEntity<RB_WeChat_Channel_ViewModel>(channelId);
            if (cmodel == null) { return null; }
            //获取标签Id
            cmodel.LabelIdList = new List<int>();
            if (!string.IsNullOrEmpty(cmodel.LableIds))
            {
                var labelList = weChat_LableRepository.GetList(new RB_WeChat_Lable_ViewModel() { Group_Id = cmodel.Group_Id, LableIds = cmodel.LableIds });
                cmodel.LabelList = labelList.Select(x => x.WXLableId).ToList();
            }

            #region 获取周期
            var weekList = weChat_ChannelWeekRepository.GetList(new RB_WeChat_ChannelWeek_ViewModel() { Group_Id = cmodel.Group_Id, ChannelId = channelId });
            if (weekList.Any())
            {
                string empIds = string.Join(",", weekList.Where(x => !string.IsNullOrEmpty(x.EmpIds)).Select(x => x.EmpIds));
                string deptIds = string.Join(",", weekList.Where(x => !string.IsNullOrEmpty(x.DeptIds)).Select(x => x.DeptIds));
                List<Employee_ViewModel> EmpList = new List<Employee_ViewModel>();
                List<RB_Department_ViewModel> DeptList = new List<RB_Department_ViewModel>();
                if (!string.IsNullOrEmpty(empIds))
                {
                    EmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = cmodel.Group_Id, QIds = empIds, IsLeave = 1 });
                }
                if (!string.IsNullOrEmpty(deptIds))
                {
                    DeptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = cmodel.Group_Id, QDeptIds = deptIds });
                }
                foreach (var item in weekList)
                {
                    item.EmpList = new List<WeekEmpDeptModel>();
                    item.DeptList = new List<WeekEmpDeptModel>();
                    if (!string.IsNullOrEmpty(item.EmpIds))
                    {
                        List<int> empIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.EmpIds + "]");
                        item.EmpList = EmpList.Where(x => empIdList.Contains(x.Id)).Select(x => new WeekEmpDeptModel()
                        {
                            Id = x.Id,
                            Name = x.EmployeeName,
                            WorkUserId = x.WorkUserId
                        }).ToList();
                    }
                    if (!string.IsNullOrEmpty(item.DeptIds))
                    {
                        List<int> deptIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.DeptIds + "]");
                        item.DeptList = DeptList.Where(x => deptIdList.Contains(x.DeptId)).Select(x => new WeekEmpDeptModel()
                        {
                            Id = x.DeptId,
                            Name = x.DeptName,
                            WorkDeptId = x.WorkDepartId
                        }).ToList();
                    }
                }
            }

            cmodel.WeekList = weekList.Where(x => x.Type == 1).ToList();
            if (cmodel.SpecialDateEnable == 1)
            {
                cmodel.SpecialWeekList = weekList.Where(x => x.Type == 2).ToList();
            }
            #endregion

            #region 人员添加上限
            if (cmodel.EmpAddLimit == 1)
            {
                cmodel.LimitList = weChat_ChannelLimitRepository.GetList(new RB_WeChat_ChannelLimit_ViewModel() { Group_Id = cmodel.Group_Id, ChannelId = channelId });

                if (!string.IsNullOrEmpty(cmodel.EmpBackUp))
                {
                    var EmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = cmodel.Group_Id, QIds = cmodel.EmpBackUp, IsLeave = 1 });
                    cmodel.EmpBackUpList = EmpList.Select(x => new WeekEmpDeptModel()
                    {
                        Id = x.Id,
                        Name = x.EmployeeName,
                        WorkUserId = x.WorkUserId
                    }).ToList();
                }
            }
            #endregion

            #region 获取欢迎语
            if (cmodel.WelcomeEnable == 1)
            {
                var welcomeList = weChat_ChannelWelcomeRepository.GetList(new RB_WeChat_ChannelWelcome_ViewModel() { Group_Id = cmodel.Group_Id, ChannelId = channelId });
                if (welcomeList.Any())
                {
                    var otherList = welcomeList.Where(x => !string.IsNullOrEmpty(x.MediumIds)).ToList();
                    if (otherList.Any())
                    {
                        string mediumIds = string.Join(",", otherList.Select(x => x.MediumIds).Distinct());
                        var mlist = weChat_MediumRepository.GetList(new RB_WeChat_Medium_ViewModel() { Group_Id = cmodel.Group_Id, MediumIds = mediumIds });
                        foreach (var item in mlist)
                        {
                            switch (item.Type)
                            {
                                case Common.Enum.WeChat.MediumTypeEnum.Text:
                                    item.TextModel = JsonHelper.DeserializeObject<MediumTextModel>(item.Content);
                                    break;
                                case Common.Enum.WeChat.MediumTypeEnum.Image:
                                    item.ImageModel = JsonHelper.DeserializeObject<MediumImageModel>(item.Content);
                                    break;
                                case Common.Enum.WeChat.MediumTypeEnum.ImgText:
                                    item.ImgTextModel = JsonHelper.DeserializeObject<MediumImgTextModel>(item.Content);
                                    break;
                                case Common.Enum.WeChat.MediumTypeEnum.Audio:
                                    item.AudioModel = JsonHelper.DeserializeObject<MediumAudioModel>(item.Content);
                                    break;
                                case Common.Enum.WeChat.MediumTypeEnum.Video:
                                    item.VideoModel = JsonHelper.DeserializeObject<MediumVideoModel>(item.Content);
                                    break;
                                case Common.Enum.WeChat.MediumTypeEnum.Applet:
                                    item.AppletModel = JsonHelper.DeserializeObject<MediumAppletModel>(item.Content);
                                    break;
                                case Common.Enum.WeChat.MediumTypeEnum.File:
                                    item.FileModel = JsonHelper.DeserializeObject<MediumFileModel>(item.Content);
                                    break;
                            }
                        }
                        foreach (var item in otherList)
                        {
                            if (!string.IsNullOrEmpty(item.MediumIds))
                            {
                                item.MediumList = mlist.Where(x => ("," + item.MediumIds + ",").Contains("," + x.Id + ",")).ToList();
                            }
                        }
                    }
                }

                cmodel.WelcomeList = welcomeList.Where(x => x.Type == 1).ToList();
                if (cmodel.WelcomeWeekEnable == 1)
                {
                    cmodel.WelcomeWeekList = welcomeList.Where(x => x.Type == 2).ToList();
                }
                if (cmodel.WelcomeSpecialEnable == 1)
                {
                    cmodel.WelcomeSpecialList = welcomeList.Where(x => x.Type == 3).ToList();
                }
            }
            #endregion

            return cmodel;
        }

        /// <summary>
        /// 新增修改渠道码
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetWeChatChannelInfo(RB_WeChat_Channel_ViewModel demodel)
        {
            var configmodel = weChat_ConfigRepository.GetList(new RB_WeChat_Config_ViewModel() { Group_Id = demodel.Group_Id, Enable = 1 }).FirstOrDefault();
            if (configmodel == null || configmodel.Enable != 1) { return "未启用企业微信，无法配置渠道码"; }

            var trans = weChat_ChannelRepository.DbTransaction;
            try
            {
                if (demodel.Id > 0)
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_WeChat_Channel_ViewModel.ChannelGroupId),demodel.ChannelGroupId },
                        { nameof(RB_WeChat_Channel_ViewModel.Name),demodel.Name },
                        { nameof(RB_WeChat_Channel_ViewModel.SkipVerify),demodel.SkipVerify },
                        { nameof(RB_WeChat_Channel_ViewModel.LableIds),demodel.LableIds },
                        { nameof(RB_WeChat_Channel_ViewModel.SpecialDateEnable),demodel.SpecialDateEnable },
                        { nameof(RB_WeChat_Channel_ViewModel.EmpAddLimit),demodel.EmpAddLimit },
                        { nameof(RB_WeChat_Channel_ViewModel.EmpBackUp),demodel.EmpBackUp },
                        { nameof(RB_WeChat_Channel_ViewModel.WelcomeEnable),demodel.WelcomeEnable },
                        { nameof(RB_WeChat_Channel_ViewModel.WelcomeWeekEnable),demodel.WelcomeWeekEnable },
                        { nameof(RB_WeChat_Channel_ViewModel.WelcomeSpecialEnable),demodel.WelcomeSpecialEnable },
                        { nameof(RB_WeChat_Channel_ViewModel.UpdateBy),demodel.UpdateBy },
                        { nameof(RB_WeChat_Channel_ViewModel.UpdateTime),demodel.UpdateTime },
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName= nameof(RB_WeChat_Channel_ViewModel.Id),
                              FiledValue= demodel.Id,
                               OperatorEnum= OperatorEnum.Equal
                        }
                    };
                    bool flag = weChat_ChannelRepository.Update(keyValues, wheres, trans);
                    if (flag) {
                        #region 首先清除子表数据
                        var weekList = weChat_ChannelWeekRepository.GetList(new RB_WeChat_ChannelWeek_ViewModel() { Group_Id = demodel.Group_Id, ChannelId = demodel.Id });
                        var limitList = weChat_ChannelLimitRepository.GetList(new RB_WeChat_ChannelLimit_ViewModel() { Group_Id = demodel.Group_Id, ChannelId = demodel.Id });
                        var welcomeList = weChat_ChannelWelcomeRepository.GetList(new RB_WeChat_ChannelWelcome_ViewModel() { Group_Id = demodel.Group_Id, ChannelId = demodel.Id });
                        
                        weChat_ChannelWeekRepository.DeleteBatch(weekList, trans);
                        weChat_ChannelLimitRepository.DeleteBatch(limitList, trans);
                        weChat_ChannelWelcomeRepository.DeleteBatch(welcomeList, trans);
                        #endregion

                        #region 再次新增数据
                        //开始插入周期
                        foreach (var item in demodel.WeekList)
                        {
                            item.Id = 0;
                            item.ChannelId = demodel.Id;
                            item.Type = 1;
                            item.EmpIds = string.Join(",", item.EmpList.Select(x => x.Id));
                            item.DeptIds = string.Join(",", item.DeptList.Select(x => x.Id));
                            item.Status = 0;
                            item.Group_Id = demodel.Group_Id;
                            item.CreateBy = demodel.CreateBy;
                            item.CreateTime = demodel.CreateTime;
                            item.UpdateBy = demodel.UpdateBy;
                            item.UpdateTime = demodel.UpdateTime;
                            weChat_ChannelWeekRepository.Insert(item, trans);
                        }
                        //开始插入特殊日期
                        if (demodel.SpecialDateEnable == 1)
                        {
                            foreach (var item in demodel.SpecialWeekList)
                            {
                                item.Id = 0;
                                item.ChannelId = demodel.Id;
                                item.Type = 2;
                                item.EmpIds = string.Join(",", item.EmpList.Select(x => x.Id));
                                item.DeptIds = string.Join(",", item.DeptList.Select(x => x.Id));
                                item.Status = 0;
                                item.Group_Id = demodel.Group_Id;
                                item.CreateBy = demodel.CreateBy;
                                item.CreateTime = demodel.CreateTime;
                                item.UpdateBy = demodel.UpdateBy;
                                item.UpdateTime = demodel.UpdateTime;
                                weChat_ChannelWeekRepository.Insert(item, trans);
                            }
                        }
                        //人员添加上限
                        if (demodel.EmpAddLimit == 1)
                        {
                            foreach (var item in demodel.LimitList)
                            {
                                item.Id = 0;
                                item.ChannelId = demodel.Id;
                                item.Status = 0;
                                item.Group_Id = demodel.Group_Id;
                                item.CreateBy = demodel.CreateBy;
                                item.CreateTime = demodel.CreateTime;
                                item.UpdateBy = demodel.UpdateBy;
                                item.UpdateTime = demodel.UpdateTime;
                                var oldlimit = limitList.Where(x => x.EmpId == item.EmpId).FirstOrDefault();
                                if (oldlimit != null) {
                                    item.ClientNum = oldlimit.ClientNum;
                                }
                                weChat_ChannelLimitRepository.Insert(item, trans);
                            }
                        }
                        //通用欢迎语
                        if (demodel.WelcomeEnable == 1)
                        {
                            foreach (var item in demodel.WelcomeList)
                            {
                                item.Id = 0;
                                item.ChannelId = demodel.Id;
                                item.Type = 1;
                                item.Status = 0;
                                item.Group_Id = demodel.Group_Id;
                                item.CreateBy = demodel.CreateBy;
                                item.CreateTime = demodel.CreateTime;
                                item.UpdateBy = demodel.UpdateBy;
                                item.UpdateTime = demodel.UpdateTime;
                                weChat_ChannelWelcomeRepository.Insert(item, trans);
                            }

                            //周期欢迎语
                            if (demodel.WelcomeWeekEnable == 1)
                            {
                                foreach (var item in demodel.WelcomeWeekList)
                                {
                                    item.Id = 0;
                                    item.ChannelId = demodel.Id;
                                    item.Type = 2;
                                    item.Status = 0;
                                    item.Group_Id = demodel.Group_Id;
                                    item.CreateBy = demodel.CreateBy;
                                    item.CreateTime = demodel.CreateTime;
                                    item.UpdateBy = demodel.UpdateBy;
                                    item.UpdateTime = demodel.UpdateTime;
                                    weChat_ChannelWelcomeRepository.Insert(item, trans);
                                }
                            }
                            //特殊日期欢迎语
                            if (demodel.WelcomeSpecialEnable == 1)
                            {
                                foreach (var item in demodel.WelcomeSpecialList)
                                {
                                    item.Id = 0;
                                    item.ChannelId = demodel.Id;
                                    item.Type = 3;
                                    item.Status = 0;
                                    item.Group_Id = demodel.Group_Id;
                                    item.CreateBy = demodel.CreateBy;
                                    item.CreateTime = demodel.CreateTime;
                                    item.UpdateBy = demodel.UpdateBy;
                                    item.UpdateTime = demodel.UpdateTime;
                                    weChat_ChannelWelcomeRepository.Insert(item, trans);
                                }
                            }
                        }
                        #endregion

                        #region 修改企业微信接口
                        //暂时屏蔽  等功能测试好了  再开启测试这个
                        var oldModel = weChat_ChannelRepository.GetEntity(demodel.Id);
                        demodel.WXConfigId = oldModel.WXConfigId;
                        var Rmsg = UpdateContactWayForQYWeiXin(demodel, configmodel);
                        if (Rmsg.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                        {
                            LogHelper.Write("修改渠道码失败：" + Rmsg.errmsg);
                            weChat_ChannelRepository.DBSession.Rollback();
                            return "更新企业已配置的「联系我」方式失败、请联系管理员";
                        }
                        #endregion
                    }
                }
                else
                {
                    //新增主表渠道码
                    int channelId = weChat_ChannelRepository.Insert(demodel, trans);
                    if (channelId > 0)
                    {
                        //开始插入周期
                        foreach (var item in demodel.WeekList)
                        {
                            item.Id = 0;
                            item.ChannelId = channelId;
                            item.Type = 1;
                            item.EmpIds = string.Join(",", item.EmpList.Select(x => x.Id));
                            item.DeptIds = string.Join(",", item.DeptList.Select(x => x.Id));
                            item.Status = 0;
                            item.Group_Id = demodel.Group_Id;
                            item.CreateBy = demodel.CreateBy;
                            item.CreateTime = demodel.CreateTime;
                            item.UpdateBy = demodel.UpdateBy;
                            item.UpdateTime = demodel.UpdateTime;
                            weChat_ChannelWeekRepository.Insert(item, trans);
                        }
                        //开始插入特殊日期
                        if (demodel.SpecialDateEnable == 1)
                        {
                            foreach (var item in demodel.SpecialWeekList)
                            {
                                item.Id = 0;
                                item.ChannelId = channelId;
                                item.Type = 2;
                                item.EmpIds = string.Join(",", item.EmpList.Select(x => x.Id));
                                item.DeptIds = string.Join(",", item.DeptList.Select(x => x.Id));
                                item.Status = 0;
                                item.Group_Id = demodel.Group_Id;
                                item.CreateBy = demodel.CreateBy;
                                item.CreateTime = demodel.CreateTime;
                                item.UpdateBy = demodel.UpdateBy;
                                item.UpdateTime = demodel.UpdateTime;
                                weChat_ChannelWeekRepository.Insert(item, trans);
                            }
                        }
                        //人员添加上限
                        if (demodel.EmpAddLimit == 1)
                        {
                            foreach (var item in demodel.LimitList)
                            {
                                item.Id = 0;
                                item.ChannelId = channelId;
                                item.Status = 0;
                                item.Group_Id = demodel.Group_Id;
                                item.CreateBy = demodel.CreateBy;
                                item.CreateTime = demodel.CreateTime;
                                item.UpdateBy = demodel.UpdateBy;
                                item.UpdateTime = demodel.UpdateTime;
                                weChat_ChannelLimitRepository.Insert(item, trans);
                            }
                        }
                        //通用欢迎语
                        if (demodel.WelcomeEnable == 1)
                        {
                            foreach (var item in demodel.WelcomeList)
                            {
                                item.Id = 0;
                                item.ChannelId = channelId;
                                item.Type = 1;
                                item.Status = 0;
                                item.Group_Id = demodel.Group_Id;
                                item.CreateBy = demodel.CreateBy;
                                item.CreateTime = demodel.CreateTime;
                                item.UpdateBy = demodel.UpdateBy;
                                item.UpdateTime = demodel.UpdateTime;
                                weChat_ChannelWelcomeRepository.Insert(item, trans);
                            }
                        }
                        //周期欢迎语
                        if (demodel.WelcomeWeekEnable == 1)
                        {
                            foreach (var item in demodel.WelcomeWeekList)
                            {
                                item.Id = 0;
                                item.ChannelId = channelId;
                                item.Type = 2;
                                item.Status = 0;
                                item.Group_Id = demodel.Group_Id;
                                item.CreateBy = demodel.CreateBy;
                                item.CreateTime = demodel.CreateTime;
                                item.UpdateBy = demodel.UpdateBy;
                                item.UpdateTime = demodel.UpdateTime;
                                weChat_ChannelWelcomeRepository.Insert(item, trans);
                            }
                        }
                        //特殊日期欢迎语
                        if (demodel.WelcomeSpecialEnable == 1)
                        {
                            foreach (var item in demodel.WelcomeSpecialList)
                            {
                                item.Id = 0;
                                item.ChannelId = channelId;
                                item.Type = 3;
                                item.Status = 0;
                                item.Group_Id = demodel.Group_Id;
                                item.CreateBy = demodel.CreateBy;
                                item.CreateTime = demodel.CreateTime;
                                item.UpdateBy = demodel.UpdateBy;
                                item.UpdateTime = demodel.UpdateTime;
                                weChat_ChannelWelcomeRepository.Insert(item, trans);
                            }
                        }

                        #region 配置企业微信接口
                        //暂时屏蔽  等功能测试好了  再开启测试这个
                        var Rmsg = AddContactWayForQYWeiXin(demodel, configmodel, channelId);
                        if (Rmsg.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                        {
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_WeChat_Channel_ViewModel.WXConfigId),Rmsg.config_id},
                                { nameof(RB_WeChat_Channel_ViewModel.WXQRCode),Rmsg.qr_code},
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName=nameof(RB_WeChat_Channel_ViewModel.Id),
                                      FiledValue= channelId,
                                       OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            weChat_ChannelRepository.Update(keyValues, wheres, trans);
                        }
                        else
                        {
                            LogHelper.Write("配置渠道码失败：" + Rmsg.errmsg);
                            weChat_ChannelRepository.DBSession.Rollback();
                            return "配置渠道码失败、请联系管理员";
                        }
                        #endregion
                    }
                }

                weChat_ChannelRepository.DBSession.Commit();
                return "";
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetWeChatChannelInfo");
                weChat_ChannelRepository.DBSession.Rollback();
                return "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 组装参数 调用企业微信配置联系我
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="configmodel"></param>
        /// <param name="channelId"></param>
        /// <returns></returns>
        private Senparc.Weixin.Work.AdvancedAPIs.External.ExternalJson.AddContactWayResult AddContactWayForQYWeiXin(RB_WeChat_Channel_ViewModel demodel, RB_WeChat_Config_ViewModel configmodel, int channelId)
        {
            DateTime NowDate = DateTime.Now;
            DateTime NowDay = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
            string NowDateStr = DateTime.Now.ToString("yyyy-MM-dd");
            List<string> EmpList = new List<string>();
            List<int> DeptList = new List<int>();
            if (demodel.SpecialDateEnable == 1)
            {
                var swlist = demodel.SpecialWeekList.Where(x => x.StartDate <= NowDay && x.EndDate >= NowDay && Convert.ToDateTime(NowDateStr + " " + x.StartHours) <= NowDate && Convert.ToDateTime(NowDateStr + " " + x.EndHours) >= NowDate).ToList();
                if (!swlist.Any())
                {
                    //使用默认数据
                    swlist = demodel.SpecialWeekList.Where(x => x.StartDate <= NowDay && x.EndDate >= NowDay && x.IsDefault == 1).ToList();
                }
                if (swlist.Any())
                {
                    var swmodel = swlist.FirstOrDefault();
                    if (swmodel.EmpList.Any())
                    {
                        string empIds = string.Join(",", swmodel.EmpList.Select(x => x.Id));
                        var elist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demodel.Group_Id, QIds = empIds, IsLeave = 1 });
                        EmpList = elist.Select(x => x.WorkUserId).ToList();
                    }
                    if (swmodel.DeptList.Any())
                    {
                        string deptIds = string.Join(",", swmodel.DeptList.Select(x => x.Id));
                        var elist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = demodel.Group_Id, QDeptIds = deptIds });
                        DeptList = elist.Where(x => x.WorkDepartId > 0).Select(x => x.WorkDepartId).ToList();
                    }
                }
            }
            if (!EmpList.Any() && !DeptList.Any())
            {
                //查询正常周期配置
                int weekNum = (int)DateTime.Now.DayOfWeek;
                var wlist = demodel.WeekList.Where(x => x.Week == weekNum && Convert.ToDateTime(NowDateStr + " " + x.StartHours) <= NowDate && Convert.ToDateTime(NowDateStr + " " + x.EndHours) >= NowDate).ToList();
                if (!wlist.Any())
                {
                    wlist = demodel.WeekList.Where(x => x.Week == weekNum && x.IsDefault == 1).ToList();
                }
                if (wlist.Any())
                {
                    var swmodel = wlist.FirstOrDefault();
                    if (swmodel.EmpList.Any())
                    {
                        string empIds = string.Join(",", swmodel.EmpList.Select(x => x.Id));
                        var elist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demodel.Group_Id, QIds = empIds, IsLeave = 1 });
                        EmpList = elist.Select(x => x.WorkUserId).ToList();
                    }
                    if (swmodel.DeptList.Any())
                    {
                        string deptIds = string.Join(",", swmodel.DeptList.Select(x => x.Id));
                        var elist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = demodel.Group_Id, QDeptIds = deptIds });
                        DeptList = elist.Where(x => x.WorkDepartId > 0).Select(x => x.WorkDepartId).ToList();
                    }
                }
            }
            if (!EmpList.Any() && !DeptList.Any())
            {
                return new Senparc.Weixin.Work.AdvancedAPIs.External.ExternalJson.AddContactWayResult()
                {
                    errcode = Senparc.Weixin.ReturnCode_Work.系统繁忙,
                    errmsg = "未查询到有效的员工/部门（AddContactWayForQYWeiXin）"
                };
            }
            #region 部门全转换为人员 因为要控制人员添加上限
            if (DeptList.Any())
            {
                string deptIds = string.Join(",", DeptList);
                var elist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demodel.Group_Id, QDeptIds = deptIds, IsLeave = 1 });
                EmpList.AddRange(elist.Select(x => x.WorkUserId));
                DeptList = new List<int>();
            }
            //验证员工是否有效
            EmpList = EmpList.Where(x => !string.IsNullOrEmpty(x)).ToList();
            if (!EmpList.Any())
            {
                return new Senparc.Weixin.Work.AdvancedAPIs.External.ExternalJson.AddContactWayResult()
                {
                    errcode = Senparc.Weixin.ReturnCode_Work.系统繁忙,
                    errmsg = "未查询到有效的员工/部门（AddContactWayForQYWeiXin）"
                };
            }
            #endregion

            string token = GetContactToken(demodel.Group_Id, configmodel);
            if (string.IsNullOrEmpty(token)) { return new Senparc.Weixin.Work.AdvancedAPIs.External.ExternalJson.AddContactWayResult() { errcode = Senparc.Weixin.ReturnCode_Work.系统繁忙, errmsg = "token获取失败" }; }
            var addModel = new Senparc.Weixin.Work.AdvancedAPIs.External.ExternalJson.AddContactWayRequest()
            {
                type = demodel.Type,
                scene = 2,
                remark = demodel.Name,
                skip_verify = demodel.SkipVerify == 1 ? false : true,
                state = "ChannelId=" + channelId,
                user = EmpList.ToArray(),
                party = DeptList.ToArray()
            };
            var Rmsg = QYWeiXinHelper.AddContactWay(token, addModel);
            return Rmsg;
        }

        /// <summary>
        /// 更新企业已配置的「联系我」方式
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="configmodel"></param>
        /// <param name="channelId"></param>
        /// <returns></returns>
        public Senparc.Weixin.Entities.WorkJsonResult UpdateContactWayForQYWeiXin(RB_WeChat_Channel_ViewModel demodel, RB_WeChat_Config_ViewModel configmodel, bool IsTimer = false)
        {
            DateTime NowDate = DateTime.Now;
            DateTime NowDay = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
            string NowDateStr = DateTime.Now.ToString("yyyy-MM-dd");
            List<WeekEmpDeptModel> EmpList = new List<WeekEmpDeptModel>();
            List<int> DeptList = new List<int>();
            if (demodel.SpecialDateEnable == 1)
            {
                var swlist = demodel.SpecialWeekList.Where(x => x.StartDate <= NowDay && x.EndDate >= NowDay && Convert.ToDateTime(NowDateStr + " " + x.StartHours) <= NowDate && Convert.ToDateTime(NowDateStr + " " + x.EndHours) >= NowDate).ToList();
                if (!swlist.Any())
                {
                    //使用默认数据
                    swlist = demodel.SpecialWeekList.Where(x => x.StartDate <= NowDay && x.EndDate >= NowDay && x.IsDefault == 1).ToList();
                }
                if (swlist.Any())
                {
                    var swmodel = swlist.FirstOrDefault();
                    if (swmodel.EmpList.Any())
                    {
                        if (IsTimer)
                        {
                            EmpList = swmodel.EmpList;//表示从 定时器来的 ， 直接赋值   订单器查询了 企业微信UserId
                        }
                        else
                        {
                            string empIds = string.Join(",", swmodel.EmpList.Select(x => x.Id));
                            var elist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demodel.Group_Id, QIds = empIds, IsLeave = 1 });
                            EmpList = elist.Select(x => new WeekEmpDeptModel()
                            {
                                Id = x.Id,
                                Name = x.EmployeeName,
                                WorkUserId = x.WorkUserId
                            }).ToList();
                        }
                    }
                    if (swmodel.DeptList.Any())
                    {
                        DeptList = swmodel.DeptList.Select(x=>x.Id).ToList();
                    }
                }
            }
            if (!EmpList.Any() && !DeptList.Any())
            {
                //查询正常周期配置
                int weekNum = (int)DateTime.Now.DayOfWeek;
                var wlist = demodel.WeekList.Where(x => x.Week == weekNum && Convert.ToDateTime(NowDateStr + " " + x.StartHours) <= NowDate && Convert.ToDateTime(NowDateStr + " " + x.EndHours) >= NowDate).ToList();
                if (!wlist.Any())
                {
                    wlist = demodel.WeekList.Where(x => x.Week == weekNum && x.IsDefault == 1).ToList();
                }
                if (wlist.Any())
                {
                    var swmodel = wlist.FirstOrDefault();
                    if (swmodel.EmpList.Any())
                    {
                        if (IsTimer)
                        {
                            EmpList = swmodel.EmpList;
                        }
                        else
                        {
                            string empIds = string.Join(",", swmodel.EmpList.Select(x => x.Id));
                            var elist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demodel.Group_Id, QIds = empIds, IsLeave = 1 });
                            EmpList = elist.Select(x => new WeekEmpDeptModel()
                            {
                                Id = x.Id,
                                Name = x.EmployeeName,
                                WorkUserId = x.WorkUserId
                            }).ToList();
                        }
                    }
                    if (swmodel.DeptList.Any())
                    {
                        DeptList = swmodel.DeptList.Select(x => x.Id).ToList();
                    }
                }
            }

            #region 部门全转换为人员 因为要控制人员添加上限
            if (DeptList.Any()) {
                string deptIds = string.Join(",", DeptList);
                var elist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demodel.Group_Id, QDeptIds = deptIds, IsLeave = 1 });
                EmpList.AddRange(elist.Select(x => new WeekEmpDeptModel()
                {
                    Id = x.Id,
                    Name = x.EmployeeName,
                    WorkUserId = x.WorkUserId
                }));
                DeptList = new List<int>();
            }
            //验证员工是否有效
            EmpList = EmpList.Where(x => !string.IsNullOrEmpty(x.WorkUserId)).ToList();
            if (!EmpList.Any())
            {
                return new Senparc.Weixin.Entities.WorkJsonResult()
                {
                    errcode = Senparc.Weixin.ReturnCode_Work.系统繁忙,
                    errmsg = demodel.Id + "未查询到有效的员工/部门（UpdateContactWayForQYWeiXin）"
                };
            }
            #endregion

            #region 验证人员添加上限
            if (demodel.EmpAddLimit == 1 && demodel.LimitList != null && demodel.LimitList.Any())
            {
                var LimitEmpList = demodel.LimitList.Where(x => x.LimitNum > 0 && x.ClientNum >= x.LimitNum).Select(x => x.EmpId).ToList();
                EmpList = EmpList.Where(x => !LimitEmpList.Contains(x.Id)).ToList();
                //使用备用人员
                if (!EmpList.Any()) {
                    //所有人都已经添加上限了  使用备用人员
                    if (IsTimer && demodel.EmpBackUpList != null && demodel.EmpBackUpList.Any())
                    {
                        EmpList = demodel.EmpBackUpList;
                    }
                    else {
                        string empIds = string.Join(",", demodel.EmpBackUpList.Select(x => x.Id));
                        var elist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demodel.Group_Id, QIds = empIds, IsLeave = 1 });
                        EmpList = elist.Select(x => new WeekEmpDeptModel()
                        {
                            Id = x.Id,
                            Name = x.EmployeeName,
                            WorkUserId = x.WorkUserId
                        }).ToList();
                    }
                    
                }
                //再次验证
                EmpList = EmpList.Where(x => !string.IsNullOrEmpty(x.WorkUserId)).ToList();
                if (!EmpList.Any()) {
                    return new Senparc.Weixin.Entities.WorkJsonResult()
                    {
                        errcode = Senparc.Weixin.ReturnCode_Work.系统繁忙,
                        errmsg = demodel.Id + "未查询到有效的备用人员（UpdateContactWayForQYWeiXin）"
                    };
                }
            }
            #endregion

            string token = GetContactTokenForTimer(demodel.Group_Id, configmodel);
            if (string.IsNullOrEmpty(token)) { return new Senparc.Weixin.Work.AdvancedAPIs.External.ExternalJson.AddContactWayResult() { errcode = Senparc.Weixin.ReturnCode_Work.系统繁忙, errmsg = "token获取失败" }; }
            var updateModel = new UpdateContactWayRequest()
            {
                config_id = demodel.WXConfigId,
                remark = demodel.Name,
                skip_verify = demodel.SkipVerify == 1 ? false : true,
                state = "ChannelId=" + demodel.Id,
                user = EmpList.Select(x => x.WorkUserId).Distinct().ToArray(),
                party = DeptList.ToArray()
            };
            var Rmsg = QYWeiXinHelper.UpdateContactWay(token, updateModel);
            return Rmsg;
        }

        /// <summary>
        /// 修改渠道码分组
        /// </summary>
        /// <param name="channelId"></param>
        /// <param name="groupId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string UpdateWeChatChannelGroup(int channelId, int groupId, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_WeChat_Channel_ViewModel.ChannelGroupId),groupId },
                { nameof(RB_WeChat_Channel_ViewModel.UpdateBy),userInfo.Id },
                { nameof(RB_WeChat_Channel_ViewModel.UpdateTime),DateTime.Now },
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName= nameof(RB_WeChat_Channel_ViewModel.Id),
                        FiledValue= channelId,
                        OperatorEnum= OperatorEnum.Equal
                }
            };
            bool flag = weChat_ChannelRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 更新人员添加上限
        /// </summary>
        /// <param name="limitModel"></param>
        /// <returns></returns>
        public string UpdateWeChatLimitClientNum(RB_WeChat_ChannelLimit_ViewModel limitModel)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                {nameof(RB_WeChat_ChannelLimit_ViewModel.ClientNum),limitModel.ClientNum }
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName=nameof(RB_WeChat_ChannelLimit_ViewModel.Id),
                      FiledValue=limitModel.Id,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = weChat_ChannelLimitRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 新增渠道码客户添加记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string AddWeChatClientRecord(RB_WeChat_ChannelRecord_ViewModel model)
        {
            bool flag = weChat_ChannelRecordRepository.Insert(model) > 0;
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 获取添加记录
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="userID"></param>
        /// <param name="externalUserID"></param>
        /// <returns></returns>
        public RB_WeChat_ChannelRecord_ViewModel GeetWeChatClientRecord(int groupId, string userID, string externalUserID)
        {
            var list = weChat_ChannelRecordRepository.GetList(new RB_WeChat_ChannelRecord_ViewModel() { Group_Id = groupId, Type = 1, WorkEmpId = userID, ExternalUserId = externalUserID });
            return list.FirstOrDefault();
        }

        /// <summary>
        /// 转移渠道码用户配置
        /// </summary>
        /// <param name="transferUserId"></param>
        /// <param name="receiveUserId"></param>
        /// <returns></returns>
        public string TransferChannelUser(int transferUserId, int receiveUserId, UserInfo userInfo)
        {
            var transferModel = accountRepository.GetEmployeeInfo(transferUserId);
            var receiveModel = accountRepository.GetEmployeeInfo(receiveUserId);
            if (transferModel == null || receiveModel == null) { return "用户不存在"; }
            string content = DateTime.Now.ToString("yyyy-MM-dd") + "用户离职，转移渠道码用户配置：由" + transferModel.EmployeeName + "(" + transferUserId + ")" + " 转移至" + receiveModel.EmployeeName + "(" + receiveUserId + ")；";

            //周期 特殊周期
            var weekList = weChat_ChannelWeekRepository.GetChannelWeekForUser(userInfo.Group_Id, transferUserId);
            if (weekList.Any()) {
                foreach (var item in weekList) {
                    List<int> empIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.EmpIds + "]");
                    empIdList = empIdList.Where(x => x != transferUserId).ToList();
                    empIdList.Add(receiveUserId);
                    item.EmpIds = string.Join(",", empIdList.Distinct());//去除一下重复
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_WeChat_ChannelWeek_ViewModel.EmpIds),item.EmpIds},
                        { nameof(RB_WeChat_ChannelWeek_ViewModel.Remark),item.Remark + content}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName= nameof(RB_WeChat_ChannelWeek_ViewModel.Id),
                              FiledValue= item.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    weChat_ChannelWeekRepository.Update(keyValues, wheres);
                }
            }
            //人员添加上限
            var limitList = weChat_ChannelLimitRepository.GetChannelLimitForUser(userInfo.Group_Id, transferUserId);
            if (limitList.Any()) {
                foreach (var item in limitList) {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_WeChat_ChannelLimit_ViewModel.EmpId),receiveUserId},
                        { nameof(RB_WeChat_ChannelLimit_ViewModel.Remark),item.Remark + content}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName= nameof(RB_WeChat_ChannelLimit_ViewModel.Id),
                              FiledValue= item.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    weChat_ChannelLimitRepository.Update(keyValues, wheres);
                }
            }
            //备用人员
            var channelList = weChat_ChannelRepository.GetChannelBackUpEmpForUser(userInfo.Group_Id, transferUserId);
            if (channelList.Any()) {
                foreach (var item in channelList) {
                    List<int> empIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.EmpBackUp + "]");
                    empIdList = empIdList.Where(x => x != transferUserId).ToList();
                    empIdList.Add(receiveUserId);
                    item.EmpBackUp = string.Join(",", empIdList.Distinct());//去除一下重复
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_WeChat_Channel_ViewModel.EmpBackUp),item.EmpBackUp},
                        { nameof(RB_WeChat_Channel_ViewModel.Remark),item.Remark + content}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName= nameof(RB_WeChat_Channel_ViewModel.Id),
                              FiledValue= item.Id,
                               OperatorEnum=OperatorEnum.Equal
                        }
                    };
                    weChat_ChannelWeekRepository.Update(keyValues, wheres);
                }
            }

            //记录日志
            weChat_ChannelLogRepository.Insert(new Model.Entity.WeChat.RB_WeChat_ChannelLog()
            {
                Id = 0,
                Type = 2,
                Content = "用户离职，转移渠道码用户配置：由" + transferModel.EmployeeName + "(" + transferUserId + ")" + " 转移至" + receiveModel.EmployeeName + "(" + receiveUserId + ")",
                CreateBy = userInfo.Id,
                Group_Id = userInfo.Group_Id,
                CreateTime = DateTime.Now,
                Status = 0
            });

            return "";
        }

        /// <summary>
        /// 获取渠道码添加客户记录
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_ChannelRecord_ViewModel> GetWeChatChannelCoustomerPageList(int pageIndex, int pageSize, out long count, RB_WeChat_ChannelRecord_ViewModel demodel)
        {
            var list = weChat_ChannelRecordRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                string empIds = string.Join(",", list.Select(x => x.EmpId).Distinct());
                var empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demodel.Group_Id, QIds = empIds });
                foreach (var item in list) {
                    var emodel = empList.Where(x => x.Id == item.EmpId).FirstOrDefault();
                    item.EmpName = emodel ?.EmployeeName ?? "";
                    item.DeptName = emodel?.DeptName ?? "";
                }
            }
            return list;
        }

        #region 定时器调用
        /// <summary>
        /// 定时器调用更新渠道活码
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public string UpdateWeChatChannelForTimer(int groupId) {
            var configmodel = weChat_ConfigRepository.GetList(new RB_WeChat_Config_ViewModel() { Group_Id = groupId, Enable = 1 }).FirstOrDefault();
            if (configmodel == null || configmodel.Enable != 1) { return "未启用企业微信，无法配置渠道码"; }

            //首先获取 所有的渠道码列表
            var channelList = weChat_ChannelRepository.GetList(new RB_WeChat_Channel_ViewModel() { Group_Id = groupId }).OrderByDescending(x => x.Type).ToList();
            if (channelList.Any()) {

                string cids = string.Join(",", channelList.Select(x => x.Id));
                #region 获取周期
                var weekList = weChat_ChannelWeekRepository.GetList(new RB_WeChat_ChannelWeek_ViewModel() { Group_Id = groupId, ChannelIds = cids });
                if (weekList.Any())
                {
                    string empIds = string.Join(",", weekList.Where(x => !string.IsNullOrEmpty(x.EmpIds)).Select(x => x.EmpIds));
                    string deptIds = string.Join(",", weekList.Where(x => !string.IsNullOrEmpty(x.DeptIds)).Select(x => x.DeptIds));
                    List<Employee_ViewModel> EmpList = new List<Employee_ViewModel>();
                    List<RB_Department_ViewModel> DeptList = new List<RB_Department_ViewModel>();
                    if (!string.IsNullOrEmpty(empIds))
                    {
                        EmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = groupId, QIds = empIds, IsLeave = 1 });
                    }
                    if (!string.IsNullOrEmpty(deptIds))
                    {
                        DeptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = groupId, QDeptIds = deptIds });
                    }
                    foreach (var item in weekList)
                    {
                        item.EmpList = new List<WeekEmpDeptModel>();
                        item.DeptList = new List<WeekEmpDeptModel>();
                        if (!string.IsNullOrEmpty(item.EmpIds))
                        {
                            List<int> empIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.EmpIds + "]");
                            item.EmpList = EmpList.Where(x => empIdList.Contains(x.Id)).Select(x => new WeekEmpDeptModel()
                            {
                                Id = x.Id,
                                Name = x.EmployeeName,
                                WorkUserId = x.WorkUserId
                            }).ToList();
                        }
                        if (!string.IsNullOrEmpty(item.DeptIds))
                        {
                            List<int> deptIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.DeptIds + "]");
                            item.DeptList = DeptList.Where(x => deptIdList.Contains(x.DeptId)).Select(x => new WeekEmpDeptModel()
                            {
                                Id = x.DeptId,
                                Name = x.DeptName,
                                WorkDeptId = x.WorkDepartId
                            }).ToList();
                        }
                    }
                }
                #endregion

                foreach (var item in channelList) {
                    item.WeekList = weekList.Where(x => x.ChannelId == item.Id && x.Type == 1).ToList();
                    if (item.SpecialDateEnable == 1)
                    {
                        item.SpecialWeekList = weekList.Where(x => x.ChannelId == item.Id && x.Type == 2).ToList();
                    }
                    System.Threading.Tasks.Task.Run(() =>
                    {
                        try
                        {
                            LogHelper.Write("channelId：" + item.Id);
                            var Rmsg = UpdateContactWayForQYWeiXin(item, configmodel, true);
                            if (Rmsg.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                            {
                                LogHelper.Write("(" + item.Id + ")更新渠道码失败，" + Rmsg.errmsg);
                            }
                            LogHelper.Write("channelId：" + item.Id + "，已结束");
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Write("(" + item.Id + ")更新渠道码失败，" + ex.Message);
                        }
                    });
                }
            }
            return "";
        }
        #endregion

        #endregion

        #region 渠道码统计

        /// <summary>
        /// 获取渠道码当日新增数据
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetWeChatChannelStatisticsForDay(int channelId, UserInfo userInfo)
        {

            var dayModel = weChat_ChannelRecordRepository.GetWeChatChannelStatisticsForDay(userInfo.Group_Id, channelId);
            int AddNum = dayModel?.AddNum ?? 0;
            int DelNum = dayModel?.DelNum ?? 0;
            int BlacklistNum = dayModel?.BlacklistNum ?? 0;
            int NetNum = AddNum - DelNum - BlacklistNum;

            return new
            {
                AddNum,
                DelNum,
                BlacklistNum,
                NetNum
            };
        }

        /// <summary>
        /// 获取渠道码曲线图统计
        /// </summary>
        /// <param name="channelId"></param>
        /// <param name="type"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetWeChatChannelStatistics(int channelId, int type, string startTime, string endTime, UserInfo userInfo)
        {
            if (type == 1 || type == 2)
            {
                if (type == 2) {
                    startTime = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                    endTime = DateTime.Now.ToString("yyyy-MM-dd");
                }

                //以日期分组查询 
                var list = weChat_ChannelRecordRepository.GetWeChatChannelStatisticsForDate(userInfo.Group_Id, channelId, startTime, endTime);
                return list.Select(x => new
                {
                    x.DateStr,
                    x.AddNum,
                    x.DelNum,
                    x.BlacklistNum,
                    NetNum = x.AddNum - x.DelNum - x.BlacklistNum
                });
            }
            else if (type == 3) {
                startTime = DateTime.Now.AddMonths(-12).ToString("yyyy-MM") + "-01";//月份 提前一年查询
                endTime = DateTime.Now.ToString("yyyy-MM-dd");

                //以月单位分组查询
                var list = weChat_ChannelRecordRepository.GetWeChatChannelStatisticsForMonth(userInfo.Group_Id, channelId, startTime, endTime);
                return list.Select(x => new
                {
                    x.DateStr,
                    x.AddNum,
                    x.DelNum,
                    x.BlacklistNum,
                    NetNum = x.AddNum - x.DelNum - x.BlacklistNum
                });
            }
            return "";
        }

        /// <summary>
        /// 获取渠道码统计详情分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="channelId"></param>
        /// <param name="type"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public List<RB_WeChat_ChannelRecord_ViewModel> GetWeChatChannelStatisticsPageList(int pageIndex,int pageSize, out long count,int channelId, int type, string startTime, string endTime, UserInfo userInfo)
        {
            if (type == 1 || type == 2)
            {
                if (type == 2)
                {
                    startTime = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                    endTime = DateTime.Now.ToString("yyyy-MM-dd");
                }

                //以日期分组查询 
                return weChat_ChannelRecordRepository.GetWeChatChannelStatisticsForDatePageList(pageIndex, pageSize, out count, userInfo.Group_Id, channelId, startTime, endTime);

            }
            else if (type == 3)
            {
                startTime = DateTime.Now.AddMonths(-12).ToString("yyyy-MM") + "-01";//月份 提前一年查询
                endTime = DateTime.Now.ToString("yyyy-MM-dd");

                //以月单位分组查询
                return weChat_ChannelRecordRepository.GetWeChatChannelStatisticsForMonthPageList(pageIndex, pageSize, out count, userInfo.Group_Id, channelId, startTime, endTime);
            }
            else
            {
                count = 0;
                return new List<RB_WeChat_ChannelRecord_ViewModel>();
            }
        }
        #endregion
    }
}
