using System;
using System.Collections.Generic;
using System.Data;
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.Entity.WeChat;
using Edu.Model.Public;
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 QYCustomerModule
    {
        /// <summary>
        /// 配置
        /// </summary>
        private readonly RB_WeChat_ConfigRepository weChat_ConfigRepository = new RB_WeChat_ConfigRepository();
        /// <summary>
        /// 客户字段
        /// </summary>
        private readonly RB_WeChat_CustomerFieldRepository weChat_CustomerFieldRepository = new RB_WeChat_CustomerFieldRepository();
        /// <summary>
        /// 客户阶段
        /// </summary>
        private readonly RB_WeChat_CustomerStageRepository weChat_CustomerStageRepository = new RB_WeChat_CustomerStageRepository();
        /// <summary>
        /// 阶段流程
        /// </summary>
        private readonly RB_WeChat_CustomerStageFlowRepository weChat_CustomerStageFlowRepository = new RB_WeChat_CustomerStageFlowRepository();
        /// <summary>
        /// 客户信息
        /// </summary>
        private readonly RB_WeChat_CustomerInfoRepository weChat_CustomerInfoRepository = new RB_WeChat_CustomerInfoRepository();
        /// <summary>
        /// 客户旅程(操作记录)
        /// </summary>
        private readonly RB_WeChat_CustomerTripRepository weChat_CustomerTripRepository = new RB_WeChat_CustomerTripRepository();
        /// <summary>
        /// 客户标签
        /// </summary>
        private readonly RB_WeChat_LableRepository weChat_LableRepository = new RB_WeChat_LableRepository();
        /// <summary>
        /// 客户操作
        /// </summary>
        private readonly RB_WeChat_CustomerConfigRepository weChat_CustomerConfigRepository = new RB_WeChat_CustomerConfigRepository();
        /// <summary>
        /// 客户线索规则
        /// </summary>
        private readonly RB_WeChat_CustomerClueRuleRepository weChat_CustomerClueRuleRepository = new RB_WeChat_CustomerClueRuleRepository();
        /// <summary>
        /// 客户库
        /// </summary>
        private readonly RB_WeChat_CustomerLibraryRepository weChat_CustomerLibraryRepository = new RB_WeChat_CustomerLibraryRepository();
        /// <summary>
        /// 部门
        /// </summary>
        private RB_DepartmentRepository departmentRepository = new RB_DepartmentRepository();
        /// <summary>
        /// 账号
        /// </summary>
        private RB_AccountRepository accountRepository = new RB_AccountRepository();

        /// <summary>
        /// 自定义查询
        /// </summary>
        private RB_CustomQueryRepository customQueryRepository = new RB_CustomQueryRepository();

        

        #region 客户字段
        /// <summary>
        /// 获取客户字段列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_CustomerField_ViewModel> GetCustomerFieldList(RB_WeChat_CustomerField_ViewModel dmodel) {
            var list = weChat_CustomerFieldRepository.GetList(dmodel);
            if (list.Any()) {

                string deptIds = string.Join(",", list.Where(x => x.DeptId > 0).Select(x => x.DeptId));
                List<RB_Department_ViewModel> dlist = new List<RB_Department_ViewModel>();
                if (!string.IsNullOrEmpty(deptIds)) {
                    dlist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = dmodel.Group_Id, QDeptIds = deptIds });
                }
                foreach (var item in list) {
                    item.OptionsList = new List<CustomerOptions>();
                    if (!string.IsNullOrEmpty(item.Options)) {
                        item.OptionsList = JsonHelper.DeserializeObject<List<CustomerOptions>>(item.Options);
                    }

                    if (item.DeptId == 0)
                    {
                        item.DeptName = "-";
                    }
                    else {
                        item.DeptName = dlist.Where(x => x.DeptId == item.DeptId).FirstOrDefault()?.DeptName ?? "";
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 新增修改客户字段
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetCustomerFiledInfo(RB_WeChat_CustomerField_ViewModel demodel)
        {
            #region 验证字段名称重复
            List<WhereHelper> wheres = new List<WhereHelper>()
            {
                new WhereHelper(){ 
                     FiledName=nameof(RB_WeChat_CustomerField_ViewModel.Name),
                      FiledValue= demodel.Name,
                       OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName=nameof(RB_WeChat_CustomerField_ViewModel.Status),
                      FiledValue= 0,
                       OperatorEnum=OperatorEnum.Equal
                },
            };
            if (demodel.Id > 0) {
                wheres.Add(new WhereHelper()
                {
                    FiledName = nameof(RB_WeChat_CustomerField_ViewModel.Id),
                    FiledValue = demodel.Id,
                    OperatorEnum = OperatorEnum.NotEqual
                });
            }
            if (weChat_CustomerFieldRepository.Exists(wheres))
            {
                return "字段名称已经存在，请核实后再试";
            }
            #endregion
            if (demodel.Id > 0)
            {
                var oldModel = weChat_CustomerFieldRepository.GetEntity(demodel.Id);
                if (oldModel.IsLock == 1 && demodel.Enable !=1) {
                    return "已锁定，无法修改启用状态";
                }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerField_ViewModel.Name), demodel.Name},
                    { nameof(RB_WeChat_CustomerField_ViewModel.Required), demodel.Required},
                    { nameof(RB_WeChat_CustomerField_ViewModel.WordNum), demodel.WordNum},
                    { nameof(RB_WeChat_CustomerField_ViewModel.InputType), demodel.InputType},
                    { nameof(RB_WeChat_CustomerField_ViewModel.Options), demodel.Options},
                    { nameof(RB_WeChat_CustomerField_ViewModel.Digits), demodel.Digits},
                    { nameof(RB_WeChat_CustomerField_ViewModel.Enable), demodel.Enable},
                    { nameof(RB_WeChat_CustomerField_ViewModel.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_WeChat_CustomerField_ViewModel.UpdateTime), DateTime.Now}
                };
                if (oldModel.IsDefault != 1)
                {
                    keyValues.Add(nameof(RB_WeChat_CustomerField_ViewModel.DeptId), demodel.DeptId);
                }

                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName= nameof(RB_WeChat_CustomerField_ViewModel.Id),
                          FiledValue= demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = weChat_CustomerFieldRepository.Update(keyValues, wheres1);
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                //查询最大的排序
                int MaxSort = weChat_CustomerFieldRepository.GetSortMax(demodel.Group_Id) + 1;
                demodel.Sort = MaxSort;

                bool flag = weChat_CustomerFieldRepository.Insert(demodel) > 0;
                return flag ? "" : "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 修改字段状态
        /// </summary>
        /// <param name="type"></param>
        /// <param name="filedId"></param>
        /// <param name="sortFiledId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerFiledState(int type, int filedId, int sortFiledId, UserInfo userInfo)
        {
            //类型  1启用  2是否必填  3删除   4排序
            var model = weChat_CustomerFieldRepository.GetEntity(filedId);
            if (model == null) { return "字段不存在"; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>();
            if (type == 1)
            {
                if (model.IsLock == 1) { return "该字段已锁定，无法修改启用状态"; }
                keyValues.Add(nameof(RB_WeChat_CustomerField_ViewModel.Enable), model.Enable == 1 ? 2 : 1);
            }
            else if (type == 2)
            {
                keyValues.Add(nameof(RB_WeChat_CustomerField_ViewModel.Required), model.Required == 1 ? 2 : 1);
            }
            else if (type == 3)
            {
                if (model.IsDefault == 1) { return "该字段无法删除"; }
                keyValues.Add(nameof(RB_WeChat_CustomerField_ViewModel.Status), 1);
            }
            else if (type == 4) {
                //排序
                int Sort = 0;
                if (sortFiledId > 0) {
                    //排此字段的后面
                    var sortModel = weChat_CustomerFieldRepository.GetEntity(sortFiledId);
                    Sort = sortModel.Sort;
                }
                // 此排序后面的字段排序都加1
                weChat_CustomerFieldRepository.SetSortNumAdd(Sort, userInfo.Group_Id);

                //当前字段的排序 = Sort +1
                keyValues.Add(nameof(RB_WeChat_CustomerField_ViewModel.Sort), Sort + 1);
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName = nameof(RB_WeChat_CustomerField_ViewModel.Id),
                      FiledValue=filedId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = weChat_CustomerFieldRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        

        #endregion

        #region 客户阶段

        /// <summary>
        /// 获取客户阶段列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_CustomerStage_ViewModel> GetCustomerStageList(RB_WeChat_CustomerStage_ViewModel demodel)
        {
            var list = weChat_CustomerStageRepository.GetList(demodel);
            if (list.Any()) {
                foreach (var item in list)
                {
                    item.OptionsList = new List<CauseOptions>();
                    if (!string.IsNullOrEmpty(item.Options))
                    {
                        item.OptionsList = JsonHelper.DeserializeObject<List<CauseOptions>>(item.Options);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 新增修改客户阶段
        /// </summary>
        /// <param name="delist"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerStageInfo(List<RB_WeChat_CustomerStage_ViewModel> delist, UserInfo userInfo)
        {
            var oldList = weChat_CustomerStageRepository.GetList(new RB_WeChat_CustomerStage_ViewModel() { Group_Id = userInfo.Group_Id });
            var delList = oldList.Where(x => !delist.Where(y => y.Id > 0).Select(y => y.Id).Contains(x.Id)).ToList();
            #region 验证需删除的这些 是否有流程在使用



            #endregion
            try
            {
                foreach (var item in delist)
                {
                    item.Status = 0;
                    item.Group_Id = userInfo.Group_Id;
                    item.CreateBy = userInfo.Id;
                    item.CreateTime = DateTime.Now;
                    item.UpdateBy = userInfo.Id;
                    item.UpdateTime = DateTime.Now;
                    if (item.Id > 0)
                    {
                        var oldModel = oldList.Where(x => x.Id == item.Id).FirstOrDefault();
                        if (oldModel == null)
                        {
                            //新增
                            weChat_CustomerStageRepository.Insert(item);
                        }
                        else
                        {
                            //修改
                            oldModel.Name = item.Name;
                            oldModel.Sort = item.Sort;
                            oldModel.Options = item.Options;
                            oldModel.IsDefault = item.IsDefault;
                            oldModel.UpdateBy = userInfo.Id;
                            oldModel.UpdateTime = DateTime.Now;
                            weChat_CustomerStageRepository.Update(oldModel);
                        }
                    }
                    else
                    {
                        //新增
                        weChat_CustomerStageRepository.Insert(item);
                    }
                }
                foreach (var item in delList)
                {
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerStage_ViewModel.Status),1}
                };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_WeChat_CustomerStage_ViewModel.Id),
                          FiledValue= item.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                    weChat_CustomerStageRepository.Update(keyValues, wheres);
                }

                #region 修改默认流程
                var flowModel = weChat_CustomerStageFlowRepository.GetList(new RB_WeChat_CustomerStageFlow_ViewModel() { Group_Id = userInfo.Group_Id, IsDefault = 1 }).FirstOrDefault();
                if (flowModel != null) {
                    flowModel.UseStage = string.Join(",", delist.Where(x => x.Type == 1).OrderBy(x => x.Sort).Select(x => x.Id));
                    flowModel.LoseCause = string.Join(",", delist.Where(x => x.Name == "已输单" && x.Type == 2).FirstOrDefault().OptionsList.Select(x => x.Id));
                    flowModel.InvalidCause = string.Join(",", delist.Where(x => x.Name == "无效" && x.Type == 2).FirstOrDefault().OptionsList.Select(x => x.Id));

                    weChat_CustomerStageFlowRepository.Update(flowModel);
                }
                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetCustomerStageInfo");
                return "出错了，请联系管理员";
            }
            return "";
        }

        /// <summary>
        /// 验证该客户阶段是否可以删除
        /// </summary>
        /// <param name="stageId"></param>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public bool ValidataCustomerStageDel(int stageId, int group_Id)
        {
            var list = weChat_CustomerStageFlowRepository.GetList(new RB_WeChat_CustomerStageFlow_ViewModel() { Group_Id = group_Id, StageId = stageId });
            if (list.Any())
            {
                return true;
            }
            else {
                return false;
            }
        }

        /// <summary>
        /// 验证原因是否可以删除
        /// </summary>
        /// <param name="causeId"></param>
        /// <param name="type"></param>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public bool ValidataCustomerCauseDel(int causeId, int type, int group_Id)
        {
            if (type == 1)
            {
                var list = weChat_CustomerStageFlowRepository.GetList(new RB_WeChat_CustomerStageFlow_ViewModel() { Group_Id = group_Id, LoseId = causeId });
                return list.Any() ? true : false;
            }
            else {
                var list = weChat_CustomerStageFlowRepository.GetList(new RB_WeChat_CustomerStageFlow_ViewModel() { Group_Id = group_Id, InvalidId = causeId });
                return list.Any() ? true : false;
            }
        }

        #endregion

        #region 客户阶段流程

        /// <summary>
        /// 获取客户阶段流程
        /// </summary>
        /// <param name="demdoel"></param>
        /// <returns></returns>
        public List<RB_WeChat_CustomerStageFlow_ViewModel> GetCustomerStageFlowList(RB_WeChat_CustomerStageFlow_ViewModel demdoel)
        {
            var list = weChat_CustomerStageFlowRepository.GetList(demdoel);
            if (list.Any()) {
                //查询部门 / 人员列表
                string deptIds = string.Join(",", list.Where(x => !string.IsNullOrEmpty(x.DeptIds) && x.DeptIds != "-1" && x.DeptIds != "0").Select(x => x.DeptIds));
                string empIds = string.Join(",", list.Where(x => !string.IsNullOrEmpty(x.EmpIds) && x.EmpIds != "-1" && x.EmpIds != "0").Select(x => x.EmpIds));
                List<RB_Department_ViewModel> deptList = new List<RB_Department_ViewModel>();
                if (!string.IsNullOrEmpty(deptIds)) {
                    //查询部门
                     deptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = demdoel.Group_Id, QDeptIds = deptIds });
                }
                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(empIds)) {
                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demdoel.Group_Id, QIds = empIds });
                }

                //查询阶段
                string stageIds = string.Join(",", list.Select(x => x.UseStage));
                var slist = weChat_CustomerStageRepository.GetList(new RB_WeChat_CustomerStage_ViewModel() { Group_Id = demdoel.Group_Id, StageIds = stageIds });

                foreach (var item in list) {
                    item.DeptEmpList = new List<DeptAndEmpModel>();
                    if (!string.IsNullOrEmpty(item.DeptIds) && item.DeptIds != "-1" && item.DeptIds != "0") {
                        var dlist = deptList.Where(x => ("," + item.DeptIds + ",").Contains("," + x.DeptId + ",")).ToList();
                        if (dlist.Any()) {
                            item.DeptEmpList.AddRange(dlist.Select(x => new DeptAndEmpModel()
                            {
                                Id = x.DeptId,
                                Name = x.DeptName,
                                Type = 1
                            }));
                        }
                    }
                    if (!string.IsNullOrEmpty(item.EmpIds) && item.EmpIds != "-1" && item.EmpIds != "0") {
                        var dlist = empList.Where(x => ("," + item.EmpIds + ",").Contains("," + x.Id + ",")).ToList();
                        if (dlist.Any())
                        {
                            item.DeptEmpList.AddRange(dlist.Select(x => new DeptAndEmpModel()
                            {
                                Id = x.Id,
                                Name = x.EmployeeName,
                                Type = 2
                            }));
                        }
                    }
                    if (item.DeptIds == "-1" && item.EmpIds == "-1") {
                        //通用
                        item.DeptEmpList.Add(new DeptAndEmpModel()
                        {
                            Id = -1,
                            Name = "通用",
                            Type = 0
                        });
                    }

                    var sclist = slist.Where(x => ("," + item.UseStage + ",").Contains("," + x.Id + ",")).ToList();
                    item.StageList = sclist.OrderBy(x => x.Sort).Select(x => x.Name).ToList();
                }
            }
            return list;
        }

        /// <summary>
        /// 获取客户阶段流程详情
        /// </summary>
        /// <param name="flowId"></param>
        /// <returns></returns>
        public RB_WeChat_CustomerStageFlow_ViewModel GetCustomerStageFlowInfo(int flowId)
        {
            var model = weChat_CustomerStageFlowRepository.GetEntity<RB_WeChat_CustomerStageFlow_ViewModel>(flowId);
            if (model == null) { return null; }

            model.DeptEmpList = new List<DeptAndEmpModel>();
            if (!string.IsNullOrEmpty(model.DeptIds) && model.DeptIds != "-1" && model.DeptIds != "0")
            {
                var dlist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = model.Group_Id, QDeptIds = model.DeptIds });
                if (dlist.Any())
                {
                    model.DeptEmpList.AddRange(dlist.Select(x => new DeptAndEmpModel()
                    {
                        Id = x.DeptId,
                        Name = x.DeptName,
                        Type = 1
                    }));
                }
            }
            if (!string.IsNullOrEmpty(model.EmpIds) && model.EmpIds != "-1" && model.EmpIds != "0")
            {
                var dlist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = model.Group_Id, QIds = model.EmpIds });                
                if (dlist.Any())
                {
                    model.DeptEmpList.AddRange(dlist.Select(x => new DeptAndEmpModel()
                    {
                        Id = x.Id,
                        Name = x.EmployeeName,
                        Type = 2
                    }));
                }
            }
            if (model.DeptIds == "-1" && model.EmpIds == "-1")
            {
                //通用
                model.DeptEmpList.Add(new DeptAndEmpModel()
                {
                    Id = -1,
                    Name = "通用",
                    Type = 0
                });
            }
            return model;
        }

        /// <summary>
        /// 保存客户阶段流程
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetCustomerStageFlowInfo(RB_WeChat_CustomerStageFlow_ViewModel demodel)
        {
            bool flag = true;
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerStageFlow_ViewModel.FlowName), demodel.FlowName},
                    { nameof(RB_WeChat_CustomerStageFlow_ViewModel.DeptIds), demodel.DeptIds},
                    { nameof(RB_WeChat_CustomerStageFlow_ViewModel.EmpIds), demodel.EmpIds},
                    { nameof(RB_WeChat_CustomerStageFlow_ViewModel.UseStage), demodel.UseStage},
                    { nameof(RB_WeChat_CustomerStageFlow_ViewModel.LoseCause), demodel.LoseCause},
                    { nameof(RB_WeChat_CustomerStageFlow_ViewModel.InvalidCause), demodel.InvalidCause},
                    { nameof(RB_WeChat_CustomerStageFlow_ViewModel.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_WeChat_CustomerStageFlow_ViewModel.UpdateTime), demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName= nameof(RB_WeChat_CustomerStageFlow_ViewModel.Id),
                          FiledValue= demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                flag = weChat_CustomerStageFlowRepository.Update(keyValues, wheres);
            }
            else {
                flag = weChat_CustomerStageFlowRepository.Insert(demodel) > 0;
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 更新阶段流程状态
        /// </summary>
        /// <param name="flowId"></param>
        /// <param name="type"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerStageFlowState(int flowId, int type, UserInfo userInfo)
        {
            var oldModel = weChat_CustomerStageFlowRepository.GetEntity(flowId);
            if (oldModel == null) { return "流程不存在"; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>();
            if (type == 1)
            {
                keyValues.Add(nameof(RB_WeChat_CustomerStageFlow_ViewModel.Enable), oldModel.Enable == 1 ? 2 : 1);//启用禁用
            }
            else if (type == 2)
            {
                keyValues.Add(nameof(RB_WeChat_CustomerStageFlow_ViewModel.Status), 1);//删除
            }
            else {
                return "类型传递有误";
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName= nameof(RB_WeChat_CustomerStageFlow_ViewModel.Id),
                      FiledValue= flowId,
                       OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = weChat_CustomerStageFlowRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        #endregion

        #region 客户操作

        /// <summary>
        /// 获取客户操作配置
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public RB_WeChat_CustomerConfig_ViewModel GetCustomerConfig(int groupId)
        {
            var model = weChat_CustomerConfigRepository.GetList(new RB_WeChat_CustomerConfig_ViewModel() { Group_Id = groupId }).FirstOrDefault();
            if (model != null) {
                model.PublicGetDeptList = new List<RB_Department_ViewModel>();
                //查询部门的一些
                if (!string.IsNullOrEmpty(model.PublicGetDept) && model.PublicGetDept != "-1")
                {
                    model.PublicGetDeptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = groupId, QDeptIds = model.PublicGetDept });
                }
                model.AbandonDeptList = new List<RB_Department_ViewModel>();
                //查询部门的一些
                if (!string.IsNullOrEmpty(model.AbandonDept) && model.AbandonDept != "-1")
                {
                    model.AbandonDeptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = groupId, QDeptIds = model.AbandonDept });
                }
                model.ApplyForTeamDeptList = new List<RB_Department_ViewModel>();
                //查询部门的一些
                if (!string.IsNullOrEmpty(model.ApplyForTeamDept) && model.ApplyForTeamDept != "-1")
                {
                    model.ApplyForTeamDeptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = groupId, QDeptIds = model.ApplyForTeamDept });
                }
                model.AddTeamDeptList = new List<RB_Department_ViewModel>();
                //查询部门的一些
                if (!string.IsNullOrEmpty(model.AddTeamDept) && model.AddTeamDept != "-1")
                {
                    model.AddTeamDeptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = groupId, QDeptIds = model.AddTeamDept });
                }
                model.TransferCustomerDeptList = new List<RB_Department_ViewModel>();
                //查询部门的一些
                if (!string.IsNullOrEmpty(model.TransferCustomerDept) && model.TransferCustomerDept != "-1")
                {
                    model.TransferCustomerDeptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = groupId, QDeptIds = model.TransferCustomerDept });
                }

                model.AbandonReasonList = new List<string>();
                if (!string.IsNullOrEmpty(model.AbandonReason)) {
                    model.AbandonReasonList = JsonHelper.DeserializeObject<List<string>>(model.AbandonReason);
                }
                model.LableList = new List<RB_WeChat_Lable_ViewModel>();
                //查询标签
                if (!string.IsNullOrEmpty(model.LableIds)) {
                    model.LableList = weChat_LableRepository.GetList(new RB_WeChat_Lable_ViewModel() { Group_Id = groupId, LableIds = model.LableIds });
                }
                model.StageList = new List<RB_WeChat_CustomerStage_ViewModel>();
                //查询阶段
                if (!string.IsNullOrEmpty(model.StageIds)) {
                    model.StageList = weChat_CustomerStageRepository.GetList(new RB_WeChat_CustomerStage_ViewModel() { Group_Id = groupId, StageIds = model.StageIds });
                }
                //查询部分客户 筛选条件
                model.AbandonKHSelect = new List<CustomerCommissionSelectModel>();
                if (!string.IsNullOrEmpty(model.AbandonSelectValue))
                {
                    model.AbandonKHSelect = JsonHelper.DeserializeObject<List<CustomerCommissionSelectModel>>(model.AbandonSelectValue);
                }

                //查询人员
                model.PublicGetEmpList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(model.PublicGetEmp) && model.PublicGetEmp != "-1")
                {
                    model.PublicGetEmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = groupId, QIds = model.PublicGetEmp });
                }
                model.AbandonEmpList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(model.AbandonEmp) && model.AbandonEmp != "-1")
                {
                    model.AbandonEmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = groupId, QIds = model.AbandonEmp });
                }
                model.ApplyForTeamEmpList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(model.ApplyForTeamEmp) && model.ApplyForTeamEmp != "-1")
                {
                    model.ApplyForTeamEmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = groupId, QIds = model.ApplyForTeamEmp });
                }
                model.AddTeamEmpList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(model.AddTeamEmp) && model.AddTeamEmp != "-1")
                {
                    model.AddTeamEmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = groupId, QIds = model.AddTeamEmp });
                }
                model.TransferCustomerEmpList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(model.TransferCustomerEmp) && model.TransferCustomerEmp != "-1")
                {
                    model.TransferCustomerEmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = groupId, QIds = model.TransferCustomerEmp });
                }

            }
            return model;
        }

        /// <summary>
        /// 保存客户操作
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetCustomerConfig(RB_WeChat_CustomerConfig_ViewModel demodel) {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.IsPublicAudit), demodel.IsPublicAudit},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.PublicGetDept), demodel.PublicGetDept},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.AbandonType), demodel.AbandonType},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.LableIds), demodel.LableIds},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.StageIds), demodel.StageIds},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.AbandonDept), demodel.AbandonDept},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.AbandonAudit), demodel.AbandonAudit},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.AbandonReason), demodel.AbandonReason},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.ApplyForTeamDept), demodel.ApplyForTeamDept},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.AddTeamDept), demodel.AddTeamDept},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.TransferCustomerDept), demodel.TransferCustomerDept},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.UpdateTime), demodel.UpdateTime},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.AbandonSelectType), demodel.AbandonSelectType},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.AbandonSelectValue), demodel.AbandonSelectValue},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_WeChat_CustomerConfig_ViewModel.Id),
                          FiledValue = demodel.Id,
                           OperatorEnum =OperatorEnum.Equal
                    }
                };
                bool flag = weChat_CustomerConfigRepository.Update(keyValues, wheres);
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                bool flag = weChat_CustomerConfigRepository.Insert(demodel) > 0;
                return flag ? "" : "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 获取放弃公海原因列表
        /// </summary>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public List<string> GetCustomerConfigAbandonReason(int group_Id)
        {
            List<string> RList = new List<string>();
            var model = weChat_CustomerConfigRepository.GetList(new RB_WeChat_CustomerConfig_ViewModel() { Group_Id = group_Id }).FirstOrDefault();
            if (model != null)
            {
                if (!string.IsNullOrEmpty(model.AbandonReason)) {
                    RList = JsonHelper.DeserializeObject<List<string>>(model.AbandonReason);
                }
            }
            return RList;
        }

        #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_CustomerInfo_ViewModel> GetCustomerInfoPageList(int pageIndex, int pageSize, out long count, RB_WeChat_CustomerInfo_ViewModel demodel)
        {
            var list = weChat_CustomerInfoRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                //客户标签
                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 stageIds = string.Join(",", list.Where(x => x.StageId > 0).Select(x => x.StageId));
                List<RB_WeChat_CustomerStage_ViewModel> StageList = new List<RB_WeChat_CustomerStage_ViewModel>();
                if (!string.IsNullOrEmpty(stageIds)) {
                    StageList = weChat_CustomerStageRepository.GetList(new RB_WeChat_CustomerStage_ViewModel() { Group_Id = demodel.Group_Id, StageIds = stageIds });
                }
                //负责人 、 公海前负责人查询
                List<Employee_ViewModel> EmpList = new List<Employee_ViewModel>();
                if (demodel.CustomerState == 3)
                {
                    string oldEmpIds = string.Join(",", list.Where(x => x.OldEmpId > 0).Select(x => x.OldEmpId));
                    if (oldEmpIds != "''")
                    {
                        EmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demodel.Group_Id, QIds = oldEmpIds });
                    }
                }
                else
                {
                    string EmpWorkUserId = "'" + string.Join("','", list.Where(x => !string.IsNullOrEmpty(x.WorkEmpId)).Select(x => x.WorkEmpId).Distinct()) + "'";
                    if (EmpWorkUserId != "''")
                    {
                        EmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demodel.Group_Id, WorkUserIds = EmpWorkUserId });
                    }
                }
                //上次跟进时间 
                //string customerIds = string.Join(",", list.Select(x => x.Id));
                //var fuList = weChat_CustomerTripRepository.GetLastFollowUpTimeList(demodel.Group_Id, customerIds);
                //自定义字段  -- 这个怎么处理呢  根据自定义子段遍历吗
                //先直接返回自定义子段
                var cFieldList = weChat_CustomerFieldRepository.GetList(new RB_WeChat_CustomerField_ViewModel() { Group_Id = demodel.Group_Id, Enable = 1 });
                foreach (var item in cFieldList) {
                    item.OptionsList = new List<CustomerOptions>();
                    if (!string.IsNullOrEmpty(item.Options))
                    {
                        item.OptionsList = JsonHelper.DeserializeObject<List<CustomerOptions>>(item.Options);
                    }
                }

                foreach (var item in list) {
                    item.LableList = LableList.Where(x => ("," + x.LableIds + ",").Contains("," + x.Id + ",")).ToList();
                    item.StageName = StageList.Where(x => x.Id == item.StageId).FirstOrDefault()?.Name ?? "";
                    if (demodel.CustomerState == 3)
                    {
                        item.OldEmpName = EmpList.Where(x => x.Id == item.OldEmpId).FirstOrDefault()?.EmployeeName ?? "";
                    }
                    else
                    {
                        var empModel = EmpList.Where(x => x.WorkUserId == item.WorkEmpId).FirstOrDefault();
                        item.EmpId = empModel?.Id ?? 0;
                        item.EmpName = (empModel?.EmployeeName ?? "") + ((empModel?.IsLeave ?? 0) == 2 ? "(已离职)" : "");
                    }

                    List<CustomerFiledContentModel> CustomValueList = new List<CustomerFiledContentModel>();
                    if (!string.IsNullOrEmpty(item.CustomContent)) {
                        var keyValueList = JsonHelper.DeserializeObject<Dictionary<string, string>>(item.CustomContent);
                        foreach (var kitem in keyValueList) {
                            CustomValueList.Add(new CustomerFiledContentModel
                            {
                                Id = Convert.ToInt32(kitem.Key.Replace("z", "")),
                                Value = kitem.Value
                            });
                        }
                    }

                    item.CustomFiledList = new List<CustomFiledContentExtend>();
                    foreach (var qitem in cFieldList) {
                        var cmodel = CustomValueList.Where(x => x.Id == qitem.Id).FirstOrDefault();
                        string value = cmodel?.Value ?? "";
                        if (qitem.Type == Common.Enum.WeChat.CustomerFieldTypeEnum.Date)
                        {
                            item.CustomFiledList.Add(new CustomFiledContentExtend()
                            {
                                Id = qitem.Id,
                                Value = value,
                                ShowValue = value != "" ? Convert.ToDateTime(value).ToString("yyyy-MM-dd") : "",
                                Name = qitem.Name,
                                Sort = qitem.Sort
                            });
                        }
                        else if (qitem.Type == Common.Enum.WeChat.CustomerFieldTypeEnum.MultiSelect)
                        {
                            var optionList = qitem.OptionsList.Where(x => ("," + value + ",").Contains("," + x.Id + ",")).ToList();
                            item.CustomFiledList.Add(new CustomFiledContentExtend()
                            {
                                Id = qitem.Id,
                                ShowValue = string.Join(",", optionList.Select(x => x.Name)),
                                Value = string.Join(",", optionList.Select(x => x.Id)),
                                Name = qitem.Name,
                                Sort = qitem.Sort
                            });
                        }
                        else if (qitem.Type == Common.Enum.WeChat.CustomerFieldTypeEnum.Radio)
                        {
                            int vInt = Convert.ToInt32(value == "" ? "0" : value);
                            var Name = qitem.OptionsList.Where(x => x.Id == vInt).FirstOrDefault()?.Name ?? "";
                            item.CustomFiledList.Add(new CustomFiledContentExtend()
                            {
                                Id = qitem.Id,
                                ShowValue = Name,
                                Value = value,
                                Name = qitem.Name,
                                Sort = qitem.Sort
                            });
                        }
                        else if (qitem.Type == Common.Enum.WeChat.CustomerFieldTypeEnum.Time)
                        {
                            item.CustomFiledList.Add(new CustomFiledContentExtend()
                            {
                                Id = qitem.Id,
                                ShowValue = value != "" ? Convert.ToDateTime(value).ToString("yyyy-MM-dd HH:mm") : "",
                                Value = value,
                                Name = qitem.Name,
                                Sort = qitem.Sort
                            });
                        }
                        else {
                            item.CustomFiledList.Add(new CustomFiledContentExtend()
                            {
                                Id = qitem.Id,
                                ShowValue = value,
                                Value = value,
                                Name = qitem.Name,
                                Sort = qitem.Sort
                            });
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取客户列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_WeChat_CustomerInfo_ViewModel> GetCustomerInfoList(RB_WeChat_CustomerInfo_ViewModel demodel) {
            return weChat_CustomerInfoRepository.GetList(demodel);
        }

        /// <summary>
        /// 获取客户信息
        /// </summary>
        /// <param name="customerId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public RB_WeChat_CustomerInfo_ViewModel GetCustomerInfo(int customerId, UserInfo userInfo)
        {
            var model = weChat_CustomerInfoRepository.GetEntity<RB_WeChat_CustomerInfo_ViewModel>(customerId);
            if (model == null) { return null; }
            //客户标签
            if (!string.IsNullOrEmpty(model.LableIds))
            {
                model.LableList = weChat_LableRepository.GetList(new RB_WeChat_Lable_ViewModel() { Group_Id = userInfo.Group_Id, LableIds = model.LableIds });
            }
            //客户阶段
            if (model.StageId > 0)
            {
                model.StageName = weChat_CustomerStageRepository.GetList(new RB_WeChat_CustomerStage_ViewModel() { Group_Id = userInfo.Group_Id, Id = model.StageId }).FirstOrDefault()?.Name ?? "";
            }
            //负责人
            if (!string.IsNullOrEmpty(model.WorkEmpId))
            {
                var empModel = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, WorkUserId = model.WorkEmpId }).FirstOrDefault();
                model.EmpId = empModel?.Id ?? 0;
                model.EmpName = (empModel?.EmployeeName ?? "") + ((empModel?.IsLeave ?? 0) == 2 ? "(已离职)" : "");
            }

            var cFieldList = weChat_CustomerFieldRepository.GetList(new RB_WeChat_CustomerField_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 });
            foreach (var item in cFieldList)
            {
                item.OptionsList = new List<CustomerOptions>();
                if (!string.IsNullOrEmpty(item.Options))
                {
                    item.OptionsList = JsonHelper.DeserializeObject<List<CustomerOptions>>(item.Options);
                }
            }

            List<CustomerFiledContentModel> CustomValueList = new List<CustomerFiledContentModel>();
            if (!string.IsNullOrEmpty(model.CustomContent))
            {
                var keyValueList = JsonHelper.DeserializeObject<Dictionary<string, string>>(model.CustomContent);
                foreach (var kitem in keyValueList)
                {
                    CustomValueList.Add(new CustomerFiledContentModel
                    {
                        Id = Convert.ToInt32(kitem.Key.Replace("z", "")),
                        Value = kitem.Value
                    });
                }
            }
            foreach (var qitem in cFieldList)
            {
                qitem.Value = CustomValueList.Where(x => x.Id == qitem.Id).FirstOrDefault()?.Value ?? "";
            }
            model.FiledDetailList = cFieldList;
            return model;
        }

        /// <summary>
        /// 设置客户信息
        /// </summary>
        /// <param name="customerId"></param>
        /// <param name="type"></param>
        /// <param name="customId"></param>
        /// <param name="value"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerInfo(int customerId, int type, int customId, string value, UserInfo userInfo)
        {
            string Description = "", Remark = "";
            var cmodel = weChat_CustomerInfoRepository.GetEntity(customerId);
            if (cmodel == null || cmodel.Group_Id != userInfo.Group_Id) { return "客户不存在"; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() { };
            if (type == 1)
            {
                Description = "编辑了客户的信息: “客户阶段”";
                string oldName = weChat_CustomerStageRepository.GetEntity(cmodel.StageId)?.Name ?? "";
                string newName = weChat_CustomerStageRepository.GetEntity(Convert.ToInt32(value))?.Name ?? "";
                Remark = $"由“{oldName}” 修改为 “{newName}”";
                //1客户阶段
                keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.StageId), Convert.ToInt32(value));
            }
            else if (type == 2)
            {
                //自定义字段
                var custModel = weChat_CustomerFieldRepository.GetEntity(customId);
                if (custModel == null) { return "字段不存在"; }

                List<CustomerFiledContentModel> FiledValueList = new List<CustomerFiledContentModel>();
                if (!string.IsNullOrEmpty(cmodel.CustomContent))
                {
                    var keyValueList = JsonHelper.DeserializeObject<Dictionary<string, string>>(cmodel.CustomContent);
                    foreach (var kitem in keyValueList)
                    {
                        FiledValueList.Add(new CustomerFiledContentModel
                        {
                            Id = Convert.ToInt32(kitem.Key.Replace("z", "")),
                            Value = kitem.Value
                        });
                    }
                }
                if (FiledValueList.Where(x => x.Id == customId).Any())
                {
                    //修改
                    var fmodel = FiledValueList.Where(x => x.Id == customId).FirstOrDefault();
                    Description = $"编辑了客户的信息: “{custModel.Name}”";
                    Remark = $"由“{fmodel.Value}” 修改为 “{value}”";
                    fmodel.Value = value;
                }
                else
                {
                    //新增
                    FiledValueList.Add(new CustomerFiledContentModel() { Id = customId, Value = value });
                    Description = $"添加了客户的信息：";
                    Remark = $"“{custModel.Name}: {value}”";
                }
                Dictionary<string, string> CustomContentKV = new Dictionary<string, string>();
                foreach (var qitem in FiledValueList)
                {
                    CustomContentKV.Add("z" + qitem.Id, qitem.Value);
                }
                keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.CustomContent), JsonHelper.Serialize(CustomContentKV));
            }
            else if (type == 3) {
                return "请调用单独接口";
            }
            else
            {
                return "type不正确";
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName= nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                      FiledValue= customerId,
                       OperatorEnum =OperatorEnum.Equal
                },
            };
            bool flag = weChat_CustomerInfoRepository.Update(keyValues, wheres);
            if (flag) {
                //记录日志
                weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                {
                    Id = 0,
                    CreateBy = userInfo.Id,
                    CreateTime = DateTime.Now,
                    CustomerId = customerId,
                    Description = Description,
                    EmpId = 0,
                    Files = "",
                    Group_Id = userInfo.Group_Id,
                    Images = "",
                    Remark = Remark,
                    Status = 0,
                    Type = Common.Enum.WeChat.CustomerTripTypeEnum.Operate,
                    UpdateBy = userInfo.Id,
                    UpdateTime = DateTime.Now
                });
            }
            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_CustomerTrip_ViewModel> GetCustomerTripPageList(int pageIndex, int pageSize, out long count, RB_WeChat_CustomerTrip_ViewModel demodel)
        {
            var list = weChat_CustomerTripRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                //员工
                string empIds = string.Join(",", list.Select(x => x.UpdateBy));
                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(empIds)) {
                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demodel.Group_Id, QIds = empIds });
                }

                foreach (var item in list) {
                    item.UpdateByName = empList.Where(x => x.Id == item.UpdateBy).FirstOrDefault()?.EmployeeName ?? "";
                    item.ImageList = new List<string>();
                    if (!string.IsNullOrEmpty(item.Images)) {
                        item.ImageList = JsonHelper.DeserializeObject<List<string>>(item.Images);
                    }
                    item.FileList = new List<Model.Public.FileModel>();
                    if (!string.IsNullOrEmpty(item.Files)) {
                        item.FileList = JsonHelper.DeserializeObject<List<FileModel>>(item.Files);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 新增客户跟进记录
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetCustomerTripFollowUpInfo(RB_WeChat_CustomerTrip_ViewModel demodel)
        {
            bool flag;
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerTrip_ViewModel.Description), demodel.Description},
                    { nameof(RB_WeChat_CustomerTrip_ViewModel.Remark), demodel.Remark},
                    { nameof(RB_WeChat_CustomerTrip_ViewModel.Images), demodel.Images},
                    { nameof(RB_WeChat_CustomerTrip_ViewModel.Files), demodel.Files},
                    { nameof(RB_WeChat_CustomerTrip_ViewModel.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_WeChat_CustomerTrip_ViewModel.UpdateTime), demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName= nameof(RB_WeChat_CustomerTrip_ViewModel.Id),
                          FiledValue= demodel.Id,
                           OperatorEnum= OperatorEnum.Equal
                    }
                };
                flag = weChat_CustomerTripRepository.Update(keyValues, wheres);
            }
            else {
                flag = weChat_CustomerTripRepository.Insert(demodel) > 0;
            }
            if (flag) {
                //更新客户表  上次跟进时间
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerInfo_ViewModel.LastFollowUpTime), DateTime.Now}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName =nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                          FiledValue = demodel.CustomerId,
                           OperatorEnum =OperatorEnum.Equal
                    }
                };
                weChat_CustomerInfoRepository.Update(keyValues, wheres);
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 删除客户旅程
        /// </summary>
        /// <param name="tripId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelCustomerTripInfo(int tripId, UserInfo userInfo)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_WeChat_CustomerTrip_ViewModel.Status), 1},
                { nameof(RB_WeChat_CustomerTrip_ViewModel.UpdateBy), userInfo.Id},
                { nameof(RB_WeChat_CustomerTrip_ViewModel.UpdateTime), DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName= nameof(RB_WeChat_CustomerTrip_ViewModel.Id),
                        FiledValue= tripId,
                        OperatorEnum= OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName= nameof(RB_WeChat_CustomerTrip_ViewModel.Group_Id),
                        FiledValue= userInfo.Group_Id,
                        OperatorEnum= OperatorEnum.Equal
                },
            };
            var flag = weChat_CustomerTripRepository.Update(keyValues, wheres);
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 初始化客户信息数据
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string InitializeCustomerInfoList(UserInfo userInfo)
        {
            //查询所有的带企业微信Id的用户列表
            var empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id });
            empList = empList.Where(x => !string.IsNullOrEmpty(x.WorkUserId)).ToList();//排除未关联企业微信的员工
            empList = empList.Where(x => x.Id == 2623).ToList();//暂时测试刘小勇账号    如果是微信删除了账号需测试-------------------
            if (empList.Any()) {
                //遍历员工列表  查询员工下所有的客户列表
                List<string> WorkUserIdList = empList.Select(x => x.WorkUserId).ToList();
                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<ExternalContactList> AllContactList = new List<ExternalContactList>();
                string next_cursor = "";
                for (int i = 0; i <= 100; i++) {
                    if (i > 0 && next_cursor == "")
                    {
                        break;//没有下一页了  退出循环
                    }
                    var Rmsg = QYWeiXinHelper.GetExternalContactInfoBatch(token, WorkUserIdList, next_cursor, 100);
                    if (Rmsg.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                    {
                        return "获取客户列表失败";
                    }
                    else
                    {
                        AllContactList.AddRange(Rmsg.external_contact_list);
                    }
                }
                if (AllContactList.Any()) {
                    //获取系统客户列表
                    var CustomerList = weChat_CustomerInfoRepository.GetList(new RB_WeChat_CustomerInfo_ViewModel() { Group_Id = userInfo.Group_Id });
                    //自定义字段
                    var FieldList = weChat_CustomerFieldRepository.GetList(new RB_WeChat_CustomerField_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 });
                    //获取所有标签列表
                    var LableList = weChat_LableRepository.GetList(new RB_WeChat_Lable_ViewModel() { Group_Id = userInfo.Group_Id });
                    //查询所有的阶段流程
                    var FlowList = weChat_CustomerStageFlowRepository.GetList(new RB_WeChat_CustomerStageFlow_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 });
                    foreach (var item in AllContactList) {
                        //与数据库客户数据对比
                        //首先看该用户是否在客户表中
                        var cmodel = CustomerList.Where(x => x.ExternalUserId == item.external_contact.external_userid && x.WorkEmpId == item.follow_info.userid).FirstOrDefault();
                        if (cmodel == null)
                        {
                            var tagWrokIdList = item.follow_info.tag_id?.ToList() ?? new List<string>();
                            var llist = LableList.Where(x => tagWrokIdList.Contains(x.WXLableId)).Select(x => x.Id).ToList();
                            #region 自定义内容
                            //暂 电话 + 性别
                            List<CustomerFiledContentModel> CustomContent = new List<CustomerFiledContentModel>();
                            string CustomerMobile = string.Join(",", item.follow_info.remark_mobiles);
                            int Sex = 0;
                            var TelModel = FieldList.Where(x => x.Name == "电话").FirstOrDefault();
                            var SexModel = FieldList.Where(x => x.Name == "性别").FirstOrDefault();
                            SexModel.OptionsList = JsonHelper.DeserializeObject<List<CustomerOptions>>(SexModel.Options);
                            if (item.external_contact.gender == 1)
                            {
                                //男
                                Sex = SexModel.OptionsList.Where(x => x.Name.Contains("男")).FirstOrDefault()?.Id ?? 0;
                            }
                            else if (item.external_contact.gender == 2) {
                                //女
                                Sex = SexModel.OptionsList.Where(x => x.Name.Contains("女")).FirstOrDefault()?.Id ?? 0;
                            }
                            else
                            {
                                //其他
                                Sex = SexModel.OptionsList.Where(x => !x.Name.Contains("女") && !x.Name.Contains("男")).FirstOrDefault()?.Id ?? 0;
                            }
                            CustomContent.Add(new CustomerFiledContentModel()
                            {
                                Id = TelModel.Id,
                                Value = CustomerMobile
                            });
                            CustomContent.Add(new CustomerFiledContentModel()
                            {
                                Id = SexModel.Id,
                                Value = Sex.ToString()
                            });
                            Dictionary<string, string> CustomContentKV = new Dictionary<string, string>();
                            foreach (var qitem in CustomContent) {
                                CustomContentKV.Add("z" + qitem.Id, qitem.Value);
                            }
                            #endregion
                            #region 阶段流程
                            //初始化阶段ID
                            int StageId = 0;
                            //获取对应的员工
                            var emodel = empList.Where(x => x.WorkUserId == item.follow_info.userid).FirstOrDefault();
                            var fmodel = FlowList.Where(x => ("," + x.DeptIds + ",").Contains("," + emodel.Dept_Id + ",") || ("," + x.EmpIds + ",").Contains("," + emodel.Id + ",")).FirstOrDefault();
                            if (fmodel == null) {
                                fmodel = FlowList.Where(x => x.DeptIds == "-1" && x.DeptIds == "-1" && x.IsDefault != 1).FirstOrDefault();
                            }
                            if (fmodel == null) {
                                fmodel = FlowList.Where(x => x.IsDefault == 1).FirstOrDefault();
                            }
                            if (fmodel != null) {
                                StageId = Convert.ToInt32(fmodel.UseStage.Split(',')[0]);//直接取第一个  保存时就需注意
                            }
                            #endregion
                            //直接新增客户信息
                            weChat_CustomerInfoRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerInfo()
                            {
                                Id = 0,
                                EmpId = emodel.Id,
                                WorkEmpId = item.follow_info.userid,
                                WorkEmpName = "",//暂不查询  需要单独调取通讯录api获取
                                ExternalUserId = item.external_contact.external_userid,
                                Status = 0,
                                Group_Id = userInfo.Group_Id,
                                CreateBy = userInfo.Id,
                                CreateTime = DateTime.Now,
                                UpdateBy = userInfo.Id,
                                UpdateTime = DateTime.Now,
                                CustomerName = string.IsNullOrEmpty(item.follow_info.remark) ? item.external_contact.name : item.follow_info.remark,
                                WeChatName = item.external_contact.name,
                                WeChatPhoto = item.external_contact.avatar,
                                CorpName = item.external_contact.corp_name,
                                CorpFullName = item.external_contact.corp_full_name,
                                CustomerType = item.external_contact.type,
                                StageId = StageId,
                                LableIds = string.Join(",", llist),
                                PersonLable = "",//暂存 查询不了
                                Source = item.follow_info.state,
                                CustomContent = JsonHelper.Serialize(CustomContentKV),
                                FriendState = 1,
                                FriendTime = ConvertToDateTime(item.follow_info.createtime.ToString()),
                                LastFollowUpTime = null,
                                CheckInNum = 0,
                                IsPublic = 2,
                                CustomerMobile = CustomerMobile,
                                Remark = "",
                                WeChatAddWay = item.follow_info.add_way,
                                AddWay = Common.Enum.WeChat.CustomerAddWayEnum.Friend,
                                CustomerState = 1
                            });
                        }
                        else { 
                            //看可更新一下资料

                        }
                    }
                }
            }
            return "";
        }

        /// <summary>
        /// 更新客户好友状态
        /// </summary>
        /// <param name="id"></param>
        public bool UpdateCustomerInfoFriendState(int id)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_WeChat_CustomerInfo_ViewModel.FriendState),1},
                { nameof(RB_WeChat_CustomerInfo_ViewModel.FriendTime),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                      FiledValue = id,
                       OperatorEnum = OperatorEnum.Equal
                }
            };
            return weChat_CustomerInfoRepository.Update(keyValues, wheres);
        }

        /// <summary>
        /// Unix时间戳转DateTime
        /// </summary>
        /// <param name="timestamp">时间戳</param>
        /// <returns></returns>
        private DateTime ConvertToDateTime(string timestamp)
        {
            DateTime time = DateTime.MinValue;
            DateTime startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.Local);
            if (timestamp.Length == 10)        //精确到秒
            {
                time = startTime.AddSeconds(double.Parse(timestamp));
            }
            else if (timestamp.Length == 13)   //精确到毫秒
            {
                time = startTime.AddMilliseconds(double.Parse(timestamp));
            }
            return time;
        }

        /// <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) || Config.IsLocal == 1)
            {
                var TelToken = QYWeiXinHelper.GetToken(configmodel.WX_CorpId, configmodel.Contact_Secret);
                if (TelToken.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                {
                    if (Config.IsLocal == 1) { return TelToken.access_token; }
                    WeChatReidsCache.TokenSet(Cache.CacheKey.QYWeChat_EmpToken_Key + Group_Id, TelToken.access_token, TelToken.expires_in - 1);
                    token = TelToken.access_token;
                }
                else
                {
                    LogHelper.Write("token获取失败，" + TelToken.errmsg);
                    return "";
                }
            }
            return token;
        }


        /// <summary>
        /// 新增客户信息
        /// </summary>
        /// <returns></returns>
        public bool AddCustomerInfoForBack(string UserID, string ExternalUserID, string State, int groupId)
        {
            //首先查询该客户是否已存在
            var cmodel = GetCustomerInfoList(new RB_WeChat_CustomerInfo_ViewModel() { Group_Id = groupId, WorkEmpId = UserID, ExternalUserId = ExternalUserID }).FirstOrDefault();
            if (cmodel == null)
            {
                //没有  需要新增
                var configmodel = weChat_ConfigRepository.GetList(new RB_WeChat_Config_ViewModel() { Group_Id = groupId, Enable = 1 }).FirstOrDefault();
                if (configmodel == null || configmodel.Enable != 1) { return false; }
                string token = GetContactToken(groupId, configmodel);
                if (string.IsNullOrEmpty(token)) { return false; }
                var ContactModel = QYWeiXinHelper.GetExternalContactInfo(token, ExternalUserID);
                if (ContactModel.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                {
                    LogHelper.Write("获取客户信息失败：" + ContactModel.errmsg);
                }
                var follow_user = ContactModel.follow_user.Where(x => x.userid == UserID).FirstOrDefault();
                string Mobile = follow_user?.remark_mobiles.FirstOrDefault() ?? "";
                bool IsInsert = false;
                if (!string.IsNullOrEmpty(Mobile))
                {
                    //判断手机号码  看是否有公司分配的 
                    var mobileList = weChat_CustomerInfoRepository.GetList(new RB_WeChat_CustomerInfo_ViewModel() { Group_Id = groupId, WorkEmpId = UserID, CustomerMobile = Mobile });
                    mobileList = mobileList.Where(x => string.IsNullOrEmpty(x.ExternalUserId)).ToList();
                    if (mobileList.Any())
                    {
                        var mmodel = mobileList.FirstOrDefault();
                        if (mmodel.FriendState != 1)
                        {
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_WeChat_CustomerInfo_ViewModel.FriendState),1},
                                { nameof(RB_WeChat_CustomerInfo_ViewModel.FriendTime),DateTime.Now},
                                { nameof(RB_WeChat_CustomerInfo_ViewModel.ExternalUserId),ExternalUserID},
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                                      FiledValue = mmodel.Id,
                                       OperatorEnum = OperatorEnum.Equal
                                }
                            };
                            return weChat_CustomerInfoRepository.Update(keyValues, wheres);
                        }
                        else {
                            IsInsert = true;
                        }
                    }
                    else
                    {
                        IsInsert = true;
                    }
                }
                else {
                    IsInsert = true;
                }
                if (IsInsert) {
                    //自定义字段
                    var FieldList = weChat_CustomerFieldRepository.GetList(new RB_WeChat_CustomerField_ViewModel() { Group_Id = groupId, Enable = 1 });
                    //获取所有标签列表
                    var LableList = weChat_LableRepository.GetList(new RB_WeChat_Lable_ViewModel() { Group_Id = groupId });
                    //查询所有的阶段流程
                    var FlowList = weChat_CustomerStageFlowRepository.GetList(new RB_WeChat_CustomerStageFlow_ViewModel() { Group_Id = groupId, Enable = 1 });
                    //插入客户明细信息
                    var tagWrokIdList = follow_user.tags.Where(x => x.type == 1).Select(x => x.tag_id).ToList();
                    var llist = LableList.Where(x => tagWrokIdList.Contains(x.WXLableId)).Select(x => x.Id).ToList();
                    #region 自定义内容
                    //暂 电话 + 性别
                    List<CustomerFiledContentModel> CustomContent = new List<CustomerFiledContentModel>();
                    string CustomerMobile = string.Join(",", follow_user.remark_mobiles);
                    int Sex = 0;
                    var TelModel = FieldList.Where(x => x.Name == "电话").FirstOrDefault();
                    var SexModel = FieldList.Where(x => x.Name == "性别").FirstOrDefault();
                    SexModel.OptionsList = JsonHelper.DeserializeObject<List<CustomerOptions>>(SexModel.Options);
                    if (ContactModel.external_contact.gender == 1)
                    {
                        //男
                        Sex = SexModel.OptionsList.Where(x => x.Name.Contains("男")).FirstOrDefault()?.Id ?? 0;
                    }
                    else if (ContactModel.external_contact.gender == 2)
                    {
                        //女
                        Sex = SexModel.OptionsList.Where(x => x.Name.Contains("女")).FirstOrDefault()?.Id ?? 0;
                    }
                    else
                    {
                        //其他
                        Sex = SexModel.OptionsList.Where(x => !x.Name.Contains("女") && !x.Name.Contains("男")).FirstOrDefault()?.Id ?? 0;
                    }
                    CustomContent.Add(new CustomerFiledContentModel()
                    {
                        Id = TelModel.Id,
                        Value = CustomerMobile
                    });
                    CustomContent.Add(new CustomerFiledContentModel()
                    {
                        Id = SexModel.Id,
                        Value = Sex.ToString()
                    });
                    Dictionary<string, string> CustomContentKV = new Dictionary<string, string>();
                    foreach (var qitem in CustomContent)
                    {
                        CustomContentKV.Add("z" + qitem.Id, qitem.Value);
                    }
                    #endregion
                    #region 阶段流程
                    //初始化阶段ID
                    int StageId = 0;
                    //获取对应的员工
                    var emodel = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = groupId, WorkUserId = UserID }).FirstOrDefault();
                    var fmodel = FlowList.Where(x => ("," + x.DeptIds + ",").Contains("," + emodel.Dept_Id + ",") || ("," + x.EmpIds + ",").Contains("," + emodel.Id + ",")).FirstOrDefault();
                    if (fmodel == null)
                    {
                        fmodel = FlowList.Where(x => x.DeptIds == "-1" && x.DeptIds == "-1" && x.IsDefault != 1).FirstOrDefault();
                    }
                    if (fmodel == null)
                    {
                        fmodel = FlowList.Where(x => x.IsDefault == 1).FirstOrDefault();
                    }
                    if (fmodel != null)
                    {
                        StageId = Convert.ToInt32(fmodel.UseStage.Split(',')[0]);//直接取第一个  保存时就需注意
                    }
                    #endregion
                    //直接新增客户信息
                    weChat_CustomerInfoRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerInfo()
                    {
                        Id = 0,
                        EmpId = emodel.Id,
                        WorkEmpId = UserID,
                        WorkEmpName = "",//暂不查询  需要单独调取通讯录api获取
                        ExternalUserId = ExternalUserID,
                        Status = 0,
                        Group_Id = groupId,
                        CreateBy = 0,
                        CreateTime = DateTime.Now,
                        UpdateBy = 0,
                        UpdateTime = DateTime.Now,
                        CustomerName = string.IsNullOrEmpty(follow_user.remark) ? ContactModel.external_contact.name : follow_user.remark,
                        WeChatName = ContactModel.external_contact.name,
                        WeChatPhoto = ContactModel.external_contact.avatar,
                        CorpName = ContactModel.external_contact.corp_name,
                        CorpFullName = ContactModel.external_contact.corp_full_name,
                        CustomerType = ContactModel.external_contact.type,
                        StageId = StageId,
                        LableIds = string.Join(",", llist),
                        PersonLable = "",//暂存 查询不了
                        Source = follow_user.state,
                        CustomContent = JsonHelper.Serialize(CustomContentKV),
                        FriendState = 1,
                        FriendTime = ConvertToDateTime(follow_user.createtime.ToString()),
                        LastFollowUpTime = null,
                        CheckInNum = 0,
                        IsPublic = 2,
                        CustomerMobile = CustomerMobile,
                        Remark = "",
                        WeChatAddWay = follow_user.add_way,
                        AddWay = Common.Enum.WeChat.CustomerAddWayEnum.Friend,
                        CustomerState =1
                    });
                }
            }
            else
            {
                //判断客户状态  修改为已添加好友
                if (cmodel.FriendState != 1)
                {
                    UpdateCustomerInfoFriendState(cmodel.Id);
                }
            }
            return true;
        }

        /// <summary>
        /// 更新客户好友状态为待添加
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="ExternalUserID"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public bool UpdateCustomerFriendStateForBack(string UserID, string ExternalUserID, int groupId) {
            var cmodel = GetCustomerInfoList(new RB_WeChat_CustomerInfo_ViewModel() { Group_Id = groupId, WorkEmpId = UserID, ExternalUserId = ExternalUserID }).FirstOrDefault();
            if (cmodel != null && cmodel.FriendState != 2) {
                //更新状态
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerInfo_ViewModel.FriendState),2},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                            FiledValue = cmodel.Id,
                            OperatorEnum = OperatorEnum.Equal
                    }
                };
                return weChat_CustomerInfoRepository.Update(keyValues, wheres);
            }
            return false;
        }

        /// <summary>
        /// 批量设置客户标签
        /// </summary>
        /// <param name="customerIds"></param>
        /// <param name="lableIds"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerLabelBatch(string customerIds, string lableIds, UserInfo userInfo)
        {
            //获取客户列表
            var clist = weChat_CustomerInfoRepository.GetList(new RB_WeChat_CustomerInfo_ViewModel() { Group_Id = userInfo.Group_Id, Q_CustomerIds = customerIds });
            if (!clist.Any()) { return "未查询到客户列表"; }
            #region 获取token 
            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获取失败，请联系管理员"; }
            #endregion
            //获取标签列表
            var labelList = weChat_LableRepository.GetList(new RB_WeChat_Lable_ViewModel() { Group_Id = userInfo.Group_Id });
            var SetLable = JsonHelper.DeserializeObject<List<int>>("[" + lableIds + "]");
            foreach (var item in clist) {
                var NowLable = new List<int>();
                if (!string.IsNullOrEmpty(item.LableIds)) {
                    NowLable = JsonHelper.DeserializeObject<List<int>>("[" + item.LableIds + "]");
                }
                var AddLable = SetLable.Where(x => !NowLable.Contains(x)).ToList();
                if (AddLable.Any()) {
                    var LabelAddList = labelList.Where(x => AddLable.Contains(x.Id)).Select(x => x.WXLableId).Distinct().ToList();
                    string labelName = string.Join(",", labelList.Where(x => AddLable.Contains(x.Id)).Select(x => x.Name));
                    #region 给客户打标签
                    if (LabelAddList.Any())
                    {
                        var lmsg = QYWeiXinHelper.SetUserCoustmerLable(token, item.WorkEmpId, item.ExternalUserId, LabelAddList);
                        if (lmsg.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                        {
                            LogHelper.Write("批量设置客户标签失败：" + lmsg.errmsg);
                        }
                        else {
                            //记录日志
                            weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                            {
                                Id = 0,
                                CreateBy = userInfo.Id,
                                CreateTime = DateTime.Now,
                                CustomerId = item.Id,
                                Description = "更新了标签：",
                                EmpId = 0,
                                Files = "",
                                Group_Id = userInfo.Group_Id,
                                Images = "",
                                Remark = "批量设置标签为：" + labelName,
                                Status = 0,
                                Type = Common.Enum.WeChat.CustomerTripTypeEnum.Operate,
                                UpdateBy = userInfo.Id,
                                UpdateTime = DateTime.Now
                            });
                        }
                    }
                    #endregion
                }
            }
            return "";
        }

        /// <summary>
        /// 设置客户标签(包含删除标签)
        /// </summary>
        /// <param name="customerId"></param>
        /// <param name="lableIds"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerLabelSingle(int customerId, string lableIds, UserInfo userInfo)
        {
            var cmodel = weChat_CustomerInfoRepository.GetEntity(customerId);
            if (cmodel == null) { return "客户信息不存在"; }
            #region 获取token 
            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获取失败，请联系管理员"; }
            #endregion
            //获取标签列表
            var labelList = weChat_LableRepository.GetList(new RB_WeChat_Lable_ViewModel() { Group_Id = userInfo.Group_Id });
            var SetLable = JsonHelper.DeserializeObject<List<int>>("[" + lableIds + "]");
            var NowLable = new List<int>();
            if (!string.IsNullOrEmpty(cmodel.LableIds))
            {
                NowLable = JsonHelper.DeserializeObject<List<int>>("[" + cmodel.LableIds + "]");
            }
            var AddLable = SetLable.Where(x => !NowLable.Contains(x)).ToList();//增加
            var DelLable = NowLable.Where(x => !SetLable.Contains(x)).ToList();//删除
            if (AddLable.Any() || DelLable.Any())
            {
                var LabelAddList = labelList.Where(x => AddLable.Contains(x.Id)).Select(x => x.WXLableId).Distinct().ToList();
                var LabelDelList = labelList.Where(x => DelLable.Contains(x.Id)).Select(x => x.WXLableId).Distinct().ToList();// ----删除标签
                string labelName = string.Join(",", labelList.Where(x => SetLable.Contains(x.Id)).Select(x => x.Name));
                #region 给客户打标签
                if (LabelAddList.Any())
                {
                    var lmsg = QYWeiXinHelper.SetUserCoustmerLable(token, cmodel.WorkEmpId, cmodel.ExternalUserId, LabelAddList);
                    if (lmsg.errcode != Senparc.Weixin.ReturnCode_Work.请求成功)
                    {
                        LogHelper.Write("设置客户标签失败：" + lmsg.errmsg);
                        return "企业微信标签更新失败";
                    }
                    else {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_WeChat_CustomerInfo_ViewModel.LableIds),lableIds }
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                                  FiledValue = customerId,
                                   OperatorEnum =OperatorEnum.Equal
                            }
                        };
                        weChat_CustomerInfoRepository.Update(keyValues, wheres);
                        //记录日志
                        weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                        {
                            Id = 0,
                            CreateBy = userInfo.Id,
                            CreateTime = DateTime.Now,
                            CustomerId = customerId,
                            Description = "更新了标签：",
                            EmpId = 0,
                            Files = "",
                            Group_Id = userInfo.Group_Id,
                            Images = "",
                            Remark = "设置标签为：" + labelName,
                            Status = 0,
                            Type = Common.Enum.WeChat.CustomerTripTypeEnum.Operate,
                            UpdateBy = userInfo.Id,
                            UpdateTime = DateTime.Now
                        });
                    }
                }
                #endregion
            }
            return "";
        }

        /// <summary>
        /// 客户转移 （在职、离职）
        /// </summary>
        /// <param name="customerIds"></param>
        /// <param name="empId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerTransfer(string customerIds, int empId, UserInfo userInfo)
        {
            //暂时先不做  有离职列表转移 +  在职所有转移； 
            var newEmpModel = accountRepository.GetEmployeeInfo(empId);
            var list = weChat_CustomerInfoRepository.GetList(new RB_WeChat_CustomerInfo_ViewModel() { Group_Id = userInfo.Group_Id, Q_CustomerIds = customerIds });
            if (list.Any()) {
                #region 验证不能转移给原负责人
                foreach (var item in list)
                {
                    if (item.WorkEmpId == newEmpModel.WorkUserId) {
                        return "客户：" + item.CustomerName + "(" + item.Id + ") 与新转入员工是同一人，请排除后再试";
                    }
                }
                #endregion
                //先验证只支持离职转交吧， 在职有限制 三个月两次
                string empIds = string.Join(",", list.Select(x => x.EmpId).Distinct());
                var emlist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, QIds = empIds });
                var zzlist = emlist.Where(x => x.LeaveStatus != Common.Enum.User.LeaveStatusEnum.Departure).ToList();
                var lzlist = emlist.Where(x => x.LeaveStatus == Common.Enum.User.LeaveStatusEnum.Departure).ToList();
                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获取失败"; }
                if (zzlist.Any()) {
                    //在职分配客户
                    foreach (var item in zzlist) {
                        List<string> CoustomerList = list.Where(x => x.WorkEmpId == item.WorkUserId).Select(x => x.ExternalUserId).ToList();
                        if (CoustomerList.Any())
                        {
                            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())
                                {
                                    string Robj = QYWeiXinHelper.TransferCostomer(token, clist, item.WorkUserId, newEmpModel.WorkUserId);
                                    if (!string.IsNullOrEmpty(Robj))
                                    {
                                        JObject parms = JObject.Parse(Robj);
                                        int errcode = parms.GetInt("errcode", -1);
                                        if (errcode == 0)
                                        {
                                            foreach (var qitem in clist) {
                                                int CustomerId = list.Where(x => x.ExternalUserId == qitem && x.WorkEmpId == item.WorkUserId).FirstOrDefault()?.Id ?? 0;
                                                #region 跟新客户原跟进人员
                                                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                                    { nameof(RB_WeChat_CustomerInfo_ViewModel.OldEmpId), item.Id},
                                                    { nameof(RB_WeChat_CustomerInfo_ViewModel.EmpId), newEmpModel.Id},
                                                    { nameof(RB_WeChat_CustomerInfo_ViewModel.WorkEmpId), newEmpModel.EmployeeName},
                                                };
                                                List<WhereHelper> wheres = new List<WhereHelper>() {
                                                    new WhereHelper(){
                                                         FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                                                          FiledValue = CustomerId,
                                                           OperatorEnum =OperatorEnum.Equal
                                                    }
                                                };
                                                weChat_CustomerInfoRepository.Update(keyValues, wheres);
                                                #endregion
                                                #region 新增流转记录
                                                weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                                                {
                                                    Id = 0,
                                                    CreateBy = userInfo.Id,
                                                    CreateTime = DateTime.Now,
                                                    CustomerId = CustomerId,
                                                    Description = "客户转移：将该客户由:" + item.EmployeeName + "转移给:" + newEmpModel.EmployeeName,
                                                    EmpId = newEmpModel.Id,
                                                    Type = Common.Enum.WeChat.CustomerTripTypeEnum.Record,
                                                    Group_Id = userInfo.Group_Id,
                                                    Remark = "",
                                                    Status = 0,
                                                    UpdateBy = userInfo.Id,
                                                    UpdateTime = DateTime.Now,
                                                });
                                                #endregion
                                            }
                                        }
                                        else
                                        {
                                            //失败
                                            return "转移客户失败，请联系管理员后再试";
                                        }
                                    }
                                    else
                                    {
                                        return "企业微信请求失败，请联系管理员";
                                    }
                                }
                            }
                        }
                    }
                }
                if (lzlist.Any()) {
                    //离职分配客户
                    foreach (var item in lzlist) {
                        List<string> CoustomerList = list.Where(x => x.WorkEmpId == item.WorkUserId).Select(x => x.ExternalUserId).ToList();
                        if (CoustomerList.Any()) {
                            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 = item.WorkUserId,
                                        takeover_userid = newEmpModel.WorkUserId,
                                        external_userid = clist
                                    };
                                    var Rmsg = QYWeiXinHelper.LeaveTransferCustomer(token, requestL);
                                    if (Rmsg.errcode == Senparc.Weixin.ReturnCode_Work.请求成功)
                                    {
                                        foreach (var qitem in clist)
                                        {
                                            int CustomerId = list.Where(x => x.ExternalUserId == qitem && x.WorkEmpId == item.WorkUserId).FirstOrDefault()?.Id ?? 0;
                                            #region 跟新客户原跟进人员
                                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                                { nameof(RB_WeChat_CustomerInfo_ViewModel.OldEmpId), item.Id},
                                                { nameof(RB_WeChat_CustomerInfo_ViewModel.EmpId), newEmpModel.Id},
                                                { nameof(RB_WeChat_CustomerInfo_ViewModel.WorkEmpId), newEmpModel.EmployeeName},
                                            };
                                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                                new WhereHelper(){
                                                        FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                                                        FiledValue = CustomerId,
                                                        OperatorEnum =OperatorEnum.Equal
                                                }
                                            };
                                            weChat_CustomerInfoRepository.Update(keyValues, wheres);
                                            #endregion
                                            #region 新增流转记录
                                            weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                                            {
                                                Id = 0,
                                                CreateBy = userInfo.Id,
                                                CreateTime = DateTime.Now,
                                                CustomerId = CustomerId,
                                                Description = "客户转移：将该客户由:" + item.EmployeeName + "转移给:" + newEmpModel.EmployeeName,
                                                EmpId = newEmpModel.Id,
                                                Type = Common.Enum.WeChat.CustomerTripTypeEnum.Record,
                                                Group_Id = userInfo.Group_Id,
                                                Remark = "",
                                                Status = 0,
                                                UpdateBy = userInfo.Id,
                                                UpdateTime = DateTime.Now,
                                            });
                                            #endregion
                                        }
                                    }
                                    else
                                    {
                                        LogHelper.Write("离职转移客户失败：" + Rmsg.errmsg);
                                        return "转移客户失败，请联系管理员后再试";
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return "";
        }

        /// <summary>
        /// 放弃客户至公海
        /// </summary>
        /// <param name="customerIds"></param>
        /// <param name="reason"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerAbandon(string customerIds, string reason, UserInfo userInfo)
        {
            #region 验证是否有权限放弃
            var configModel = weChat_CustomerConfigRepository.GetList(new RB_WeChat_CustomerConfig_ViewModel() { Group_Id = userInfo.Group_Id }).FirstOrDefault();
            if (configModel != null) {
                if (configModel.AbandonDept != "-1" || configModel.AbandonEmp != "-1") {
                    bool IsHavePermission = false;
                    if (configModel.AbandonEmp != "-1") { 
                        if((","+ configModel.AbandonEmp + ",").Contains("," + userInfo.Id + ","))
                        {
                            IsHavePermission = true;
                        }
                    }
                    if (IsHavePermission == false && configModel.AbandonDept != "-1") {
                        if (("," + configModel.AbandonDept + ",").Contains("," + userInfo.DeptId + ","))
                        {
                            IsHavePermission = true;
                        }
                    }
                    if (!IsHavePermission) {
                        return "您没有权限放弃客户至公海";
                    }
                }
            }
            #endregion
            var list = weChat_CustomerInfoRepository.GetList(new RB_WeChat_CustomerInfo_ViewModel() { Group_Id = userInfo.Group_Id, Q_CustomerIds = customerIds });
            foreach (var item in list)
            {
                #region 验证客户权限
                if (configModel != null && configModel.AbandonType == 2)
                {
                    #region 客户自定义字段转化

                    List<CustomerFiledContentModel> CustomValueList = new List<CustomerFiledContentModel>();
                    if (!string.IsNullOrEmpty(item.CustomContent))
                    {
                        var keyValueList = JsonHelper.DeserializeObject<Dictionary<string, string>>(item.CustomContent);
                        foreach (var kitem in keyValueList)
                        {
                            CustomValueList.Add(new CustomerFiledContentModel
                            {
                                Id = Convert.ToInt32(kitem.Key.Replace("z", "")),
                                Value = kitem.Value
                            });
                        }
                    }
                    #endregion
                    //部分客户验证
                    if (!string.IsNullOrEmpty(configModel.AbandonSelectValue)) {
                        //转化
                        List<CustomerCommissionSelectModel> AbandonCList = JsonHelper.DeserializeObject<List<CustomerCommissionSelectModel>>(configModel.AbandonSelectValue);

                        bool IsSure = false;
                        if (configModel.AbandonSelectType == 1)
                        {
                            //并且  所有条件必须满足
                            bool ConditionOk = false;
                            foreach (var citem in AbandonCList)
                            {
                                string cvValue = "";
                                if (citem.IsCustom == 1)
                                {
                                    var cvModel = CustomValueList.Where(x => x.Id == citem.Id).FirstOrDefault();
                                    if (cvModel == null) { ConditionOk = false; break; }
                                    cvValue = cvModel.Value;
                                }
                                else if (citem.IsCustom == 2)
                                {
                                    //标签
                                    cvValue = item.LableIds;
                                }
                                else if (citem.IsCustom == 3)
                                {
                                    //客户阶段
                                    cvValue = item.StageId.ToString();
                                }
                                //写成一个通用方法
                                ConditionOk = GetConditionValidata(ConditionOk, citem, cvValue);
                                if (ConditionOk == false) { break; }
                            }
                            //所有条件都必须Ok才算Ok
                            if (ConditionOk) { IsSure = true; }
                        }
                        else
                        {
                            //或者  满足一个条件就可以
                            bool ConditionOk = false;
                            foreach (var citem in AbandonCList)
                            {
                                string cvValue = "";
                                if (citem.IsCustom == 1)
                                {
                                    var cvModel = CustomValueList.Where(x => x.Id == citem.Id).FirstOrDefault();
                                    if (cvModel == null) { continue; }
                                    cvValue = cvModel.Value;
                                }
                                else if (citem.IsCustom == 2)
                                {
                                    //标签
                                    cvValue = item.LableIds;
                                }
                                else if (citem.IsCustom == 3)
                                {
                                    //客户阶段
                                    cvValue = item.StageId.ToString();
                                }
                                //写成一个通用方法
                                ConditionOk = GetConditionValidata(ConditionOk, citem, cvValue);
                                if (ConditionOk) { break; }
                            }
                            //所有条件都必须Ok才算Ok
                            if (ConditionOk) { IsSure = true; }
                        }
                        if (!IsSure)
                        {
                            return "客户" + item.CustomerName + "(" + item.Id + ") 无法放弃至公海";
                        }
                    }
                }
                #endregion
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerInfo_ViewModel.CustomerState), 3},
                    { nameof(RB_WeChat_CustomerInfo_ViewModel.AbandonReason), reason},
                    { nameof(RB_WeChat_CustomerInfo_ViewModel.AbandonTime), DateTime.Now},
                    { nameof(RB_WeChat_CustomerInfo_ViewModel.UpdateBy), userInfo.Id},
                    { nameof(RB_WeChat_CustomerInfo_ViewModel.UpdateTime), DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                          FiledValue= item.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = weChat_CustomerInfoRepository.Update(keyValues, wheres);
                if (flag) {
                    weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                    {
                        Id = 0,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        CustomerId = item.Id,
                        Description = "放弃客户至公海",
                        EmpId = 0,
                        Files = "",
                        Group_Id = userInfo.Group_Id,
                        Images = "",
                        Remark = reason,
                        Status = 0,
                        Type = Common.Enum.WeChat.CustomerTripTypeEnum.Record,
                        UpdateBy = userInfo.Id,
                        UpdateTime = DateTime.Now
                    });
                }
            }
            return "";
        }

        /// <summary>
        /// 删除客户
        /// </summary>
        /// <param name="customerIds"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string DelCustomerInfo(string customerIds, UserInfo userInfo)
        {
            var list = weChat_CustomerInfoRepository.GetList(new RB_WeChat_CustomerInfo_ViewModel() { Group_Id = userInfo.Group_Id, Q_CustomerIds = customerIds });
            foreach (var item in list) {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerInfo_ViewModel.Status), 1},
                    { nameof(RB_WeChat_CustomerInfo_ViewModel.UpdateBy), userInfo.Id},
                    { nameof(RB_WeChat_CustomerInfo_ViewModel.UpdateTime), DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                          FiledValue= item.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = weChat_CustomerInfoRepository.Update(keyValues, wheres);
                if (flag) {
                    weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                    {
                        Id = 0,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        CustomerId = item.Id,
                        Description = "删除客户",
                        EmpId = 0,
                        Files = "",
                        Group_Id = userInfo.Group_Id,
                        Images = "",
                        Remark = "",
                        Status = 0,
                        Type = Common.Enum.WeChat.CustomerTripTypeEnum.Operate,
                        UpdateBy = userInfo.Id,
                        UpdateTime = DateTime.Now
                    });
                }
            }
            return "";
        }
        #endregion

        #region 客户线索

        /// <summary>
        /// 获取线索规则配置
        /// </summary>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public RB_WeChat_CustomerConfig_ViewModel GetCustomerClueRule(int group_Id)
        {
            return weChat_CustomerConfigRepository.GetList(new RB_WeChat_CustomerConfig_ViewModel() { Group_Id = group_Id }).FirstOrDefault();
        }

        /// <summary>
        /// 保存客户线索规则配置
        /// </summary>
        /// <param name="clueType"></param>
        /// <param name="clueAllotWay"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerClueRuleConfig(int clueType, int clueAllotWay, UserInfo userInfo)
        {
            var model = weChat_CustomerConfigRepository.GetList(new RB_WeChat_CustomerConfig_ViewModel() { Group_Id = userInfo.Group_Id }).FirstOrDefault();
            if (model != null)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.ClueType), clueType},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.ClueAllotWay), clueAllotWay},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.UpdateBy), userInfo.Id},
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.UpdateTime), DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_WeChat_CustomerConfig_ViewModel.Id),
                          FiledValue = model.Id,
                           OperatorEnum =OperatorEnum.Equal
                    }
                };
                bool flag = weChat_CustomerConfigRepository.Update(keyValues, wheres);
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                return "未初始化客户配置";
            }
        }

        /// <summary>
        /// 获取客户线索规则列表
        /// </summary>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public List<RB_WeChat_CustomerClueRule_ViewModel> GetCustomerClueRuleList(int group_Id)
        {
            var Rlist = new List<RB_WeChat_CustomerClueRule_ViewModel>();
            var list = weChat_CustomerClueRuleRepository.GetList(new RB_WeChat_CustomerClueRule_ViewModel() { Group_Id = group_Id });
            var defaultModel = list.Where(x => x.IsDefault == 1).FirstOrDefault();
            if (defaultModel == null) {
                defaultModel = new RB_WeChat_CustomerClueRule_ViewModel()
                {
                    Id = 0,
                    IsDefault = 1,
                    DeptIds = "-1",
                    EmpIds = "-1",
                    RuleAllotWay = 1,
                    Sort = 0
                };
            }
            Rlist.Add(defaultModel);//添加默认的
            var otherList = list.Where(x => x.IsDefault != 1).ToList();
            if (otherList.Any()) {
                Rlist.AddRange(otherList.OrderBy(x => x.Sort));
            }

            if (Rlist.Any()) {
                //组装  条件 + 部门 + 员工
                //查询所有的字段
                var fieldList = weChat_CustomerFieldRepository.GetList(new RB_WeChat_CustomerField_ViewModel() { Group_Id = group_Id });
                foreach (var item in fieldList)
                {
                    item.OptionsList = new List<CustomerOptions>();
                    if (!string.IsNullOrEmpty(item.Options))
                    {
                        item.OptionsList = JsonHelper.DeserializeObject<List<CustomerOptions>>(item.Options);
                    }
                }
                //查询部门 员工
                string deptIds = string.Join(",", Rlist.Where(x => !string.IsNullOrEmpty(x.DeptIds) && x.DeptIds != "-1").Select(x => x.DeptIds));
                List<RB_Department_ViewModel> deptList = new List<RB_Department_ViewModel>();
                if (!string.IsNullOrEmpty(deptIds)) {
                    deptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = group_Id, QDeptIds = deptIds });
                }
                string empIds = string.Join(",", Rlist.Where(x => !string.IsNullOrEmpty(x.EmpIds) && x.EmpIds != "-1").Select(x => x.EmpIds));
                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(empIds))
                {
                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = group_Id, QIds = empIds });
                }

                foreach (var item in Rlist) {
                    //反序列化条件列表 List<CustomerCommissionSelectModel> ConditionList
                    item.ConditionList = new List<CustomerCommissionSelectModel>();
                    item.ConditionStrList = new List<string>();
                    if (!string.IsNullOrEmpty(item.RuleSelectValue)) {
                        item.ConditionList = JsonHelper.DeserializeObject<List<CustomerCommissionSelectModel>>(item.RuleSelectValue);
                    }
                    int num = 1;
                    int count = item.ConditionList.Count();
                    foreach (var qitem in item.ConditionList)
                    {
                        string conditionStr = "", destiption = "";
                        conditionStr = GetConditionName(qitem, conditionStr);

                        if (qitem.IsCustom == 1)
                        {
                            var fieldModel = fieldList.Where(x => x.Id == qitem.Id).FirstOrDefault();
                            if (fieldModel == null) { continue; }
                            destiption = $"{fieldModel.Name} {conditionStr} ";

                            switch (fieldModel.Type) {
                                case Common.Enum.WeChat.CustomerFieldTypeEnum.Radio:
                                    int vInt = Convert.ToInt32(qitem.StartValue == "" ? "0" : qitem.StartValue);
                                    var Name = fieldModel.OptionsList.Where(x => x.Id == vInt).FirstOrDefault()?.Name ?? "";
                                    destiption += "“" + Name + "”";
                                    break;
                                case Common.Enum.WeChat.CustomerFieldTypeEnum.MultiSelect:
                                    var optionList = fieldModel.OptionsList.Where(x => ("," + qitem.StartValue + ",").Contains("," + x.Id + ",")).ToList();
                                    destiption += "“" + string.Join(",", optionList.Select(x => x.Name)) + "”";
                                    break;
                                case Common.Enum.WeChat.CustomerFieldTypeEnum.Time:
                                    destiption += "“" + qitem.StartValue + "至" + qitem.EndValue + "”";
                                    break;
                                default:
                                    destiption += "“" + qitem.StartValue + "”";
                                    break;
                            }
                        }
                        else if (qitem.IsCustom == 2)
                        {
                            destiption = $"标签 {conditionStr} ";
                            //标签
                            if (!string.IsNullOrEmpty(qitem.StartValue))
                            {
                                var lableList = weChat_LableRepository.GetList(new RB_WeChat_Lable_ViewModel() { Group_Id = group_Id, LableIds = qitem.StartValue });
                                destiption += "“" + string.Join(",", lableList.Select(x => x.Name)) + "”";
                            }
                        }
                        item.ConditionStrList.Add(destiption + "的客户" + ((count == 1 || num == count) ? "" : (item.RuleSelectType == 1 ? " 且" : " 或")));
                        num++;
                    }

                    item.DeptList = new List<RB_Department_ViewModel>();
                    item.EmpList = new List<Employee_ViewModel>();
                    if (!string.IsNullOrEmpty(item.DeptIds) && item.DeptIds != "-1") {
                        item.DeptList = deptList.Where(x => ("," + item.DeptIds + ",").Contains("," + x.DeptId + ",")).ToList();
                    }
                    if (!string.IsNullOrEmpty(item.EmpIds) && item.EmpIds != "-1")
                    {
                        item.EmpList = empList.Where(x => ("," + item.EmpIds + ",").Contains("," + x.Id + ",")).ToList();
                    }
                }
            }

            return Rlist.OrderBy(x => x.Sort).ToList();
        }

        /// <summary>
        /// 获取线索信息
        /// </summary>
        /// <param name="ruleId"></param>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public RB_WeChat_CustomerClueRule_ViewModel GetCustomerClueRuleInfo(int ruleId, int group_Id)
        {           
            var Rlist = weChat_CustomerClueRuleRepository.GetList(new RB_WeChat_CustomerClueRule_ViewModel() { Group_Id = group_Id, Id = ruleId });
            if (Rlist.Any())
            {
                //组装  条件 + 部门 + 员工
                //查询所有的字段
                var fieldList = weChat_CustomerFieldRepository.GetList(new RB_WeChat_CustomerField_ViewModel() { Group_Id = group_Id });
                foreach (var item in fieldList)
                {
                    item.OptionsList = new List<CustomerOptions>();
                    if (!string.IsNullOrEmpty(item.Options))
                    {
                        item.OptionsList = JsonHelper.DeserializeObject<List<CustomerOptions>>(item.Options);
                    }
                }
                //查询部门 员工
                string deptIds = string.Join(",", Rlist.Where(x => !string.IsNullOrEmpty(x.DeptIds) && x.DeptIds != "-1").Select(x => x.DeptIds));
                List<RB_Department_ViewModel> deptList = new List<RB_Department_ViewModel>();
                if (!string.IsNullOrEmpty(deptIds))
                {
                    deptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = group_Id, QDeptIds = deptIds });
                }
                string empIds = string.Join(",", Rlist.Where(x => !string.IsNullOrEmpty(x.EmpIds) && x.EmpIds != "-1").Select(x => x.EmpIds));
                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(empIds))
                {
                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = group_Id, QIds = empIds });
                }

                foreach (var item in Rlist)
                {
                    //反序列化条件列表 List<CustomerCommissionSelectModel> ConditionList
                    item.ConditionList = new List<CustomerCommissionSelectModel>();
                    item.ConditionStrList = new List<string>();
                    if (!string.IsNullOrEmpty(item.RuleSelectValue))
                    {
                        item.ConditionList = JsonHelper.DeserializeObject<List<CustomerCommissionSelectModel>>(item.RuleSelectValue);
                    }
                    int num = 1;
                    int count = item.ConditionList.Count();
                    foreach (var qitem in item.ConditionList)
                    {
                        string conditionStr = "", destiption = "";
                        conditionStr = GetConditionName(qitem, conditionStr);

                        if (qitem.IsCustom == 1)
                        {
                            var fieldModel = fieldList.Where(x => x.Id == qitem.Id).FirstOrDefault();
                            if (fieldModel == null) { continue; }
                            destiption = $"{fieldModel.Name} {conditionStr} ";

                            switch (fieldModel.Type)
                            {
                                case Common.Enum.WeChat.CustomerFieldTypeEnum.Radio:
                                    int vInt = Convert.ToInt32(qitem.StartValue == "" ? "0" : qitem.StartValue);
                                    var Name = fieldModel.OptionsList.Where(x => x.Id == vInt).FirstOrDefault()?.Name ?? "";
                                    destiption += "“" + Name + "”";
                                    break;
                                case Common.Enum.WeChat.CustomerFieldTypeEnum.MultiSelect:
                                    var optionList = fieldModel.OptionsList.Where(x => ("," + qitem.StartValue + ",").Contains("," + x.Id + ",")).ToList();
                                    destiption += "“" + string.Join(",", optionList.Select(x => x.Name)) + "”";
                                    break;
                                case Common.Enum.WeChat.CustomerFieldTypeEnum.Time:
                                    destiption += "“" + qitem.StartValue + "至" + qitem.EndValue + "”";
                                    break;
                                default:
                                    destiption += "“" + qitem.StartValue + "”";
                                    break;
                            }
                        }
                        else if (qitem.IsCustom == 2)
                        {
                            destiption = $"标签 {conditionStr} ";
                            //标签
                            if (!string.IsNullOrEmpty(qitem.StartValue))
                            {
                                var lableList = weChat_LableRepository.GetList(new RB_WeChat_Lable_ViewModel() { Group_Id = group_Id, LableIds = qitem.StartValue });
                                destiption += "“" + string.Join(",", lableList.Select(x => x.Name)) + "”";
                            }
                        }
                        item.ConditionStrList.Add(destiption + "的客户" + ((count == 1 || num == count) ? "" : (item.RuleSelectType == 1 ? " 且" : " 或")));
                        num++;
                    }

                    item.DeptList = new List<RB_Department_ViewModel>();
                    item.EmpList = new List<Employee_ViewModel>();
                    if (!string.IsNullOrEmpty(item.DeptIds) && item.DeptIds != "-1")
                    {
                        item.DeptList = deptList.Where(x => ("," + item.DeptIds + ",").Contains("," + x.DeptId + ",")).ToList();
                    }
                    if (!string.IsNullOrEmpty(item.EmpIds) && item.EmpIds != "-1")
                    {
                        item.EmpList = empList.Where(x => ("," + item.EmpIds + ",").Contains("," + x.Id + ",")).ToList();
                    }
                }
            }

            return Rlist.FirstOrDefault();
        }

        /// <summary>
        /// 新增修改线索规则
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetCustomerClueRuleInfo(RB_WeChat_CustomerClueRule_ViewModel demodel)
        {
            if (demodel.Id > 0)
            {
                var oldModel = weChat_CustomerClueRuleRepository.GetEntity(demodel.Id);
                if (oldModel == null) { return "规则不存在"; }
                if (oldModel.IsDefault == 1) {
                    demodel.RuleSelectValue = "";
                }
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerClueRule_ViewModel.RuleSelectType), demodel.RuleSelectType},
                    { nameof(RB_WeChat_CustomerClueRule_ViewModel.RuleSelectValue), demodel.RuleSelectValue},
                    { nameof(RB_WeChat_CustomerClueRule_ViewModel.DeptIds), demodel.DeptIds},
                    { nameof(RB_WeChat_CustomerClueRule_ViewModel.EmpIds), demodel.EmpIds},
                    { nameof(RB_WeChat_CustomerClueRule_ViewModel.RuleAllotWay), demodel.RuleAllotWay},
                    { nameof(RB_WeChat_CustomerClueRule_ViewModel.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_WeChat_CustomerClueRule_ViewModel.UpdateTime), demodel.UpdateTime}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_WeChat_CustomerClueRule_ViewModel.Id),
                          FiledValue = demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = weChat_CustomerClueRuleRepository.Update(keyValues, wheres);
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                demodel.Sort = 1;
                int Id = weChat_CustomerClueRuleRepository.Insert(demodel);
                if (Id > 0) {
                    //更新后面规则排序
                    weChat_CustomerClueRuleRepository.UpdateLastClueRuleSortAdd(demodel.Group_Id, Id);
                }
                return Id > 0 ? "" : "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 设置线索规则状态
        /// </summary>
        /// <param name="ruleId"></param>
        /// <param name="type"></param>
        /// <param name="targetId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerClueRuleState(int ruleId, int type, int targetId, UserInfo userInfo)
        {
            if (type == 1)
            {
                //转移
                var oldModel = weChat_CustomerClueRuleRepository.GetEntity(ruleId);
                if (targetId == 0)
                {
                    if (oldModel.Sort == 1) { return ""; }
                    //排在第一个
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_WeChat_CustomerClueRule_ViewModel.Sort), 1},
                        { nameof(RB_WeChat_CustomerClueRule_ViewModel.UpdateBy), userInfo.Id},
                        { nameof(RB_WeChat_CustomerClueRule_ViewModel.UpdateTime), DateTime.Now}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName = nameof(RB_WeChat_CustomerClueRule_ViewModel.Id),
                              FiledValue = ruleId,
                               OperatorEnum = OperatorEnum.Equal
                        }
                    };
                    bool flag = weChat_CustomerClueRuleRepository.Update(keyValues, wheres);
                    if (flag)
                    {
                        //更新后面的排序 +1 至到当前的
                        weChat_CustomerClueRuleRepository.UpdateLastClueRuleSortAdd(userInfo.Group_Id, ruleId, 1, oldModel.Sort);
                    }
                    return flag ? "" : "出错了，请联系管理员";
                }
                else
                {
                    var tarModel = weChat_CustomerClueRuleRepository.GetEntity(targetId);//移这个的后面
                    if (oldModel.Sort > tarModel.Sort)
                    {
                        if (oldModel.Sort == tarModel.Sort + 1)
                        {
                            //说明就在屁股后面
                            return "";
                        }
                        int newSort = tarModel.Sort + 1;
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_WeChat_CustomerClueRule_ViewModel.Sort), newSort},
                            { nameof(RB_WeChat_CustomerClueRule_ViewModel.UpdateBy), userInfo.Id},
                            { nameof(RB_WeChat_CustomerClueRule_ViewModel.UpdateTime), DateTime.Now}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName = nameof(RB_WeChat_CustomerClueRule_ViewModel.Id),
                                  FiledValue = ruleId,
                                   OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        bool flag = weChat_CustomerClueRuleRepository.Update(keyValues, wheres);
                        if (flag)
                        {
                            //更新后面的排序 +1 至到当前的
                            weChat_CustomerClueRuleRepository.UpdateLastClueRuleSortAdd(userInfo.Group_Id, ruleId, newSort, oldModel.Sort);
                        }
                        return flag ? "" : "出错了，请联系管理员";
                    }
                    else {
                        Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                            { nameof(RB_WeChat_CustomerClueRule_ViewModel.Sort), tarModel.Sort},
                            { nameof(RB_WeChat_CustomerClueRule_ViewModel.UpdateBy), userInfo.Id},
                            { nameof(RB_WeChat_CustomerClueRule_ViewModel.UpdateTime), DateTime.Now}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName = nameof(RB_WeChat_CustomerClueRule_ViewModel.Id),
                                  FiledValue = ruleId,
                                   OperatorEnum = OperatorEnum.Equal
                            }
                        };
                        bool flag = weChat_CustomerClueRuleRepository.Update(keyValues, wheres);
                        if (flag) {
                            //更新前面排序 -1 
                            weChat_CustomerClueRuleRepository.UpdateLastClueRuleSortSubtract(userInfo.Group_Id, ruleId, oldModel.Sort, tarModel.Sort);
                        }
                        return flag ? "" : "出错了，请联系管理员";
                    }
                }
            }
            else if (type == 2)
            {
                //删除
                var oldModel = weChat_CustomerClueRuleRepository.GetEntity(ruleId);
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerClueRule_ViewModel.Status), 1},
                    { nameof(RB_WeChat_CustomerClueRule_ViewModel.UpdateBy), userInfo.Id},
                    { nameof(RB_WeChat_CustomerClueRule_ViewModel.UpdateTime), DateTime.Now}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_WeChat_CustomerClueRule_ViewModel.Id),
                          FiledValue = ruleId,
                           OperatorEnum = OperatorEnum.Equal
                    }
                };
                bool flag = weChat_CustomerClueRuleRepository.Update(keyValues, wheres);
                if (flag) {
                    //更新后面的排序
                    weChat_CustomerClueRuleRepository.UpdateLastClueRuleSortAdd(userInfo.Group_Id, ruleId, oldModel.Sort);
                }
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                return "类型有误";
            }
        }

        /// <summary>
        /// 获取条件关联名称
        /// </summary>
        /// <param name="qitem"></param>
        /// <param name="conditionStr"></param>
        /// <returns></returns>
        private string GetConditionName(CustomerCommissionSelectModel qitem, string conditionStr)
        {
            switch (qitem.Type)
            {
                case 1:
                    switch (qitem.Direction)
                    {
                        case 1:
                            conditionStr = "包含所有"; break;
                        case 2:
                            conditionStr = "包含任意"; break;
                        case 3:
                            conditionStr = "不包含"; break;
                        case 4:
                            conditionStr = "为空"; break;
                        case 5:
                            conditionStr = "不为空"; break;
                    }
                    break;
                case 2:
                    switch (qitem.Direction)
                    {
                        case 1:
                            conditionStr = "等于"; break;
                        case 2:
                            conditionStr = "不等于"; break;
                        case 3:
                            conditionStr = "为空"; break;
                        case 4:
                            conditionStr = "不为空"; break;
                        case 5:
                            conditionStr = "模糊匹配"; break;
                    }
                    break;
                case 5:
                    switch (qitem.Direction)
                    {
                        case 1:
                            conditionStr = "等于"; break;
                        case 2:
                            conditionStr = "大于"; break;
                        case 3:
                            conditionStr = "大于等于"; break;
                        case 4:
                            conditionStr = "小于"; break;
                        case 5:
                            conditionStr = "小于等于"; break;
                    }
                    break;
            }

            return conditionStr;
        }


        /// <summary>
        /// 新增线索
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetCustomerClueInfo(RB_WeChat_CustomerInfo_ViewModel demodel)
        {
            #region 验证手机号码
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.CustomerMobile),
                      FiledValue = demodel.CustomerMobile,
                       OperatorEnum =OperatorEnum.Equal
                },
                new WhereHelper(){
                     FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Group_Id),
                      FiledValue = demodel.Group_Id,
                       OperatorEnum =OperatorEnum.Equal
                }
            };
            bool fvalidata = weChat_CustomerInfoRepository.ValidataMobile(new RB_WeChat_CustomerInfo_ViewModel() { Group_Id = demodel.Group_Id, CustomerMobile = demodel.CustomerMobile });
            if (fvalidata) { return "手机号码已经存在"; }
            #endregion
            int Id = weChat_CustomerInfoRepository.Insert(demodel);
            bool flag = Id > 0;
            if (flag) {
                //记录日志
                string Remark = "";
                foreach (var item in demodel.CustomFiledList)
                {
                    Remark += item.Name + ":" + item.ShowValue + "、";
                }
                weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                {
                    Id = 0,
                    CreateBy = demodel.CreateBy,
                    CreateTime = DateTime.Now,
                    CustomerId = Id,
                    Description = "创建了该客户",
                    EmpId = 0,
                    Files = "",
                    Group_Id = demodel.Group_Id,
                    Images = "",
                    Remark = Remark,
                    Status = 0,
                    Type = Common.Enum.WeChat.CustomerTripTypeEnum.Operate,
                    UpdateBy = demodel.UpdateBy,
                    UpdateTime = DateTime.Now
                });
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 设置线索状态
        /// </summary>
        /// <param name="customerIds"></param>
        /// <param name="type"></param>
        /// <param name="empIds"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerClueState(string customerIds, int type, string empIds, UserInfo userInfo)
        {
            //获取用户列表
            var clist = weChat_CustomerInfoRepository.GetList(new RB_WeChat_CustomerInfo_ViewModel() { Group_Id = userInfo.Group_Id, Q_CustomerIds = customerIds });
            if (clist.Where(x => x.CustomerState == 2).Any()) { return "客户状态不正确"; }
            bool flag = false;
            string Remark = "";

            //类型  1有效线索  2无效线索  3待回访  4直接分配（员工ID） 5重置无效线索
            Dictionary<string, object> keyValues = new Dictionary<string, object>();
            if (type == 1)
            {
                //有效线索   如果开启自动分配、需自动分配   未开启的话 =》待分配
                //获取配置
                var cconfig = weChat_CustomerConfigRepository.GetList(new RB_WeChat_CustomerConfig_ViewModel() { Group_Id = userInfo.Group_Id }).FirstOrDefault();
                if ((cconfig?.ClueType ?? 1) == 2)
                {
                    //获取所有分配规则
                    var list = weChat_CustomerClueRuleRepository.GetList(new RB_WeChat_CustomerClueRule_ViewModel() { Group_Id = userInfo.Group_Id });
                    var defaultRuleModel = list.Where(x => x.IsDefault == 1).FirstOrDefault();
                    if (defaultRuleModel == null)
                    {
                        defaultRuleModel = new RB_WeChat_CustomerClueRule_ViewModel()
                        {
                            Id = 0,
                            IsDefault = 1,
                            DeptIds = "-1",
                            EmpIds = "-1",
                            RuleAllotWay = 1,
                            Sort = 0
                        };
                    }
                    var otherRuleList = list.Where(x => x.IsDefault != 1).OrderBy(x => x.Sort).ToList();//根据sort升序
                    foreach (var qqitem in otherRuleList) {
                        qqitem.ConditionList = new List<CustomerCommissionSelectModel>();
                        if (!string.IsNullOrEmpty(qqitem.RuleSelectValue))
                        {
                            qqitem.ConditionList = JsonHelper.DeserializeObject<List<CustomerCommissionSelectModel>>(qqitem.RuleSelectValue);
                        }
                    }
                    //获取所有字段
                    var cFieldList = weChat_CustomerFieldRepository.GetList(new RB_WeChat_CustomerField_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 });

                    Dictionary<int, int> customerRuleList = new Dictionary<int, int>();//客户匹配的规则，   key:规则  value:客户
                    //开始匹配规则
                    foreach (var item in clist) {
                        //处理客户自定义字段
                        List<CustomerFiledContentModel> CustomValueList = new List<CustomerFiledContentModel>();
                        if (!string.IsNullOrEmpty(item.CustomContent))
                        {
                            var keyValueList = JsonHelper.DeserializeObject<Dictionary<string, string>>(item.CustomContent);
                            foreach (var kitem in keyValueList)
                            {
                                CustomValueList.Add(new CustomerFiledContentModel
                                {
                                    Id = Convert.ToInt32(kitem.Key.Replace("z", "")),
                                    Value = kitem.Value
                                });
                            }
                        }
                        //开始验证
                        //首先根据 规则排序 依次验证该用户 适用哪一个规则 
                        bool IsSure = false;
                        foreach (var ritem in otherRuleList) {
                            IsSure = false;
                            if (ritem.RuleSelectType == 1)
                            {
                                //并且  所有条件必须满足
                                bool ConditionOk = false;
                                foreach (var citem in ritem.ConditionList)
                                {
                                    string cvValue = "";
                                    if (citem.IsCustom == 1)
                                    {
                                        var fieldModel = cFieldList.Where(x => x.Id == citem.Id).FirstOrDefault();
                                        if (fieldModel == null) { continue; }
                                        var cvModel = CustomValueList.Where(x => x.Id == citem.Id).FirstOrDefault();
                                        cvValue = cvModel.Value;
                                    }
                                    else if (citem.IsCustom == 2)
                                    {
                                        //标签
                                        cvValue = item.LableIds;
                                    }
                                    else if (citem.IsCustom == 3)
                                    {
                                        //客户阶段
                                        cvValue = item.StageId.ToString();
                                    }
                                    //写成一个通用方法
                                    ConditionOk = GetConditionValidata(ConditionOk, citem, cvValue);
                                    if (ConditionOk == false) { break; }
                                }
                                //所有条件都必须Ok才算Ok
                                if (ConditionOk) { IsSure = true; }
                            }
                            else {
                                //或者  满足一个条件就可以
                                bool ConditionOk = false;
                                foreach (var citem in ritem.ConditionList)
                                {                                    
                                    string cvValue = "";
                                    if (citem.IsCustom == 1)
                                    {
                                        var fieldModel = cFieldList.Where(x => x.Id == citem.Id).FirstOrDefault();
                                        if (fieldModel == null) { continue; }
                                        var cvModel = CustomValueList.Where(x => x.Id == citem.Id).FirstOrDefault();
                                        cvValue = cvModel.Value;
                                    }
                                    else if (citem.IsCustom == 2)
                                    {
                                        //标签
                                        cvValue = item.LableIds;
                                    }
                                    else if (citem.IsCustom == 3)
                                    {
                                        //客户阶段
                                        cvValue = item.StageId.ToString();
                                    }
                                    //写成一个通用方法
                                    ConditionOk = GetConditionValidata(ConditionOk, citem, cvValue);
                                    if (ConditionOk) { break; }
                                }
                                //所有条件都必须Ok才算Ok
                                if (ConditionOk) { IsSure = true; }
                            }
                            if (IsSure) {
                                customerRuleList.Add(ritem.Id, item.Id);
                                break;
                            }
                        }

                        if (!IsSure) {
                            //继续匹配为默认的
                            customerRuleList.Add(defaultRuleModel.Id, item.Id);
                        }
                    }

                    //开始根据规则来 分配客户
                    if (customerRuleList.Any()) {
                        List<int> RuleList = customerRuleList.Select(x => x.Key).ToList();
                        foreach (var ruleId in RuleList) {
                            var ruleModel = otherRuleList.Where(x => x.Id == ruleId).FirstOrDefault();
                            if (ruleModel == null) { ruleModel = defaultRuleModel; }
                            //获取规则下所有的用户
                            List<Employee_ViewModel> elist = new List<Employee_ViewModel>();
                            if (!string.IsNullOrEmpty(ruleModel.DeptIds)) {
                                var edlist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, QDeptIds = ruleModel.DeptIds });
                                if (edlist.Any())
                                {
                                    elist.AddRange(edlist);
                                }
                            }
                            if (!string.IsNullOrEmpty(ruleModel.EmpIds)) {
                                var edlist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, QIds = ruleModel.EmpIds });
                                if (edlist.Any())
                                {
                                    elist.AddRange(edlist);
                                }
                            }
                            elist = elist.Distinct().ToList();//去除重复的  看怎么排序分配 (这个排序可能涉及一套分配规则)
                            var empIdList = elist.Select(x => x.Id).ToList();
                            //获取当前的客户
                            var customerVL = customerRuleList.Where(x => x.Key == ruleId).Select(x => x.Value).ToList();
                            var customerList = clist.Where(x => customerVL.Contains(x.Id)).ToList();
                            //开始分配
                            if (ruleModel.RuleAllotWay == 1)
                            {
                                //依次分配                    
                                int Num = 1;
                                foreach (var item in customerList)
                                {
                                    //获取用户ID
                                    int empId = GetRankEmpId(empIdList, Num);//获取顺序用户
                                    var empModel = elist.Where(x => x.Id == empId).FirstOrDefault();
                                    keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.EmpId), empId);
                                    keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.WorkEmpId), empId);
                                    List<WhereHelper> wheres = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                                              FiledValue = item,
                                               OperatorEnum =OperatorEnum.Equal
                                        }
                                    };
                                    weChat_CustomerInfoRepository.Update(keyValues, wheres);
                                    weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                                    {
                                        Id = 0,
                                        CreateBy = userInfo.Id,
                                        CreateTime = DateTime.Now,
                                        CustomerId = item.Id,
                                        Description = userInfo.AccountName + "提交有效线索，系统依次将该客户分配给" + (empModel?.EmployeeName ?? ""),
                                        EmpId = 0,
                                        Files = "",
                                        Group_Id = userInfo.Group_Id,
                                        Images = "",
                                        Remark = "",
                                        Status = 0,
                                        Type = Common.Enum.WeChat.CustomerTripTypeEnum.Operate,
                                        UpdateBy = userInfo.Id,
                                        UpdateTime = DateTime.Now
                                    });
                                    Num++;
                                }
                            }
                            else {
                                //随机分配
                                foreach (var item in customerList)
                                {
                                    //获取用户ID
                                    int empId = GetRandomEmpId(empIdList);//获取随机用户
                                    var empModel = elist.Where(x => x.Id == empId).FirstOrDefault();
                                    keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.EmpId), empId);
                                    keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.WorkEmpId), empModel?.WorkUserId ?? "");
                                    List<WhereHelper> wheres = new List<WhereHelper>() {
                                        new WhereHelper(){
                                             FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                                              FiledValue = item,
                                               OperatorEnum =OperatorEnum.Equal
                                        }
                                    };
                                    weChat_CustomerInfoRepository.Update(keyValues, wheres);
                                    weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                                    {
                                        Id = 0,
                                        CreateBy = userInfo.Id,
                                        CreateTime = DateTime.Now,
                                        CustomerId = item.Id,
                                        Description = userInfo.AccountName + "提交有效线索，系统随机将该客户分配给" + (empModel?.EmployeeName ?? ""),
                                        EmpId = 0,
                                        Files = "",
                                        Group_Id = userInfo.Group_Id,
                                        Images = "",
                                        Remark = "",
                                        Status = 0,
                                        Type = Common.Enum.WeChat.CustomerTripTypeEnum.Operate,
                                        UpdateBy = userInfo.Id,
                                        UpdateTime = DateTime.Now
                                    });
                                    
                                }
                            }
                        }
                    }

                    //怎么验证重复分配（重复分配之后  又该怎么分配）???????????????????  待确认

                }
                else {
                    //进入待分配
                    keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.ClueState), 4);//已转客户
                    keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.AllotState), 1);//待分配
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                            FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                            FiledValue = customerIds,
                            OperatorEnum =OperatorEnum.IN
                        }
                    };
                    flag = weChat_CustomerInfoRepository.Update(keyValues, wheres);
                    Remark = "修改线索为待分配";
                }
            }
            else if (type == 2)
            {
                if (clist.Where(x => x.ClueState == 3 || x.ClueState == 4).Any()) { return "客户状态不正确"; }
                keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.ClueState), 3);//无效线索
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                            FiledValue = customerIds,
                            OperatorEnum =OperatorEnum.IN
                    }
                };
                flag = weChat_CustomerInfoRepository.Update(keyValues, wheres);
                Remark = "修改线索为无效线索";
            }
            else if (type == 3)
            {
                if (clist.Where(x => x.ClueState != 1).Any()) { return "客户状态不正确"; }
                keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.ClueState), 2);//待回访
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                            FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                            FiledValue = customerIds,
                            OperatorEnum =OperatorEnum.IN
                    }
                };
                flag = weChat_CustomerInfoRepository.Update(keyValues, wheres);
                Remark = "修改线索为待回访";
            }
            else if (type == 4)
            {
                List<int> empIdList = JsonHelper.DeserializeObject<List<int>>("[" + empIds + "]");
                //获取配置
                var cconfig = weChat_CustomerConfigRepository.GetList(new RB_WeChat_CustomerConfig_ViewModel() { Group_Id = userInfo.Group_Id }).FirstOrDefault();
                //获取用户
                var elist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = userInfo.Group_Id, QIds = empIds });
                if (elist.Where(x => string.IsNullOrEmpty(x.WorkUserId)).Any()) { return "有用户未绑定企业微信"; }
                //直接分配
                keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.ClueState), 4);
                keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.AllotState), 2);//已分配
                keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.CustomerState), 1);//正常客户

                List<int> customerIdList = JsonHelper.DeserializeObject<List<int>>("[" + customerIds + "]");
                var trans = weChat_CustomerInfoRepository.DbTransaction;
                try
                {
                    if ((cconfig?.ClueAllotWay ?? 1) == 1)
                    {
                        //依次分配                    
                        int Num = 1;
                        foreach (var item in customerIdList) {
                            //获取用户ID
                            int empId = GetRankEmpId(empIdList, Num);//获取顺序用户
                            var empModel = elist.Where(x => x.Id == empId).FirstOrDefault();
                            keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.EmpId), empId);
                            keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.WorkEmpId), empModel?.WorkUserId ?? "");
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                                      FiledValue = item,
                                       OperatorEnum =OperatorEnum.Equal
                                }
                            };
                            flag = weChat_CustomerInfoRepository.Update(keyValues, wheres);
                            if (flag == false)
                            {
                                weChat_CustomerInfoRepository.DBSession.Rollback();
                            }
                            else {
                                weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                                {
                                    Id = 0,
                                    CreateBy = userInfo.Id,
                                    CreateTime = DateTime.Now,
                                    CustomerId = item,
                                    Description = userInfo.AccountName + "将该客户分配给" + (empModel?.EmployeeName ?? ""),
                                    EmpId = 0,
                                    Files = "",
                                    Group_Id = userInfo.Group_Id,
                                    Images = "",
                                    Remark = "",
                                    Status = 0,
                                    Type = Common.Enum.WeChat.CustomerTripTypeEnum.Operate,
                                    UpdateBy = userInfo.Id,
                                    UpdateTime = DateTime.Now
                                });
                            }
                            Num++;
                        }
                    }
                    else {
                        //随机分配
                        foreach (var item in customerIdList)
                        {
                            //获取用户ID
                            int empId = GetRandomEmpId(empIdList);//获取随机用户
                            var empModel = elist.Where(x => x.Id == empId).FirstOrDefault();
                            keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.EmpId), empId);
                            keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.WorkEmpId), empModel?.WorkUserId ?? "");
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                                      FiledValue = item,
                                       OperatorEnum =OperatorEnum.Equal
                                }
                            };
                            flag = weChat_CustomerInfoRepository.Update(keyValues, wheres);
                            if (flag == false)
                            {
                                weChat_CustomerInfoRepository.DBSession.Rollback();
                            }
                            else {
                                weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                                {
                                    Id = 0,
                                    CreateBy = userInfo.Id,
                                    CreateTime = DateTime.Now,
                                    CustomerId = item,
                                    Description = userInfo.AccountName + "将该客户分配给" + (empModel?.EmployeeName ?? ""),
                                    EmpId = 0,
                                    Files = "",
                                    Group_Id = userInfo.Group_Id,
                                    Images = "",
                                    Remark = "",
                                    Status = 0,
                                    Type = Common.Enum.WeChat.CustomerTripTypeEnum.Operate,
                                    UpdateBy = userInfo.Id,
                                    UpdateTime = DateTime.Now
                                });
                            }
                        }
                    }
                    weChat_CustomerInfoRepository.DBSession.Commit();
                }
                catch (Exception ex)
                {
                    LogHelper.Write(ex, "SetCustomerClueState");
                    weChat_CustomerInfoRepository.DBSession.Rollback();
                }
            }
            else if (type == 5) {
                if (clist.Where(x => x.ClueState != 3).Any()) { return "客户状态不正确"; }
                keyValues.Add(nameof(RB_WeChat_CustomerInfo_ViewModel.ClueState), 1);//未处理
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                        FiledName = nameof(RB_WeChat_CustomerInfo_ViewModel.Id),
                        FiledValue = customerIds,
                        OperatorEnum =OperatorEnum.IN
                    }
                };
                flag = weChat_CustomerInfoRepository.Update(keyValues, wheres);
                Remark = "修改线索为未处理";
            }
            else
            {
                return "类型有误";
            }

            if (flag) {
                //新增日志
                if (!string.IsNullOrEmpty(Remark))
                {
                    //暂时   -----------------------------------
                    foreach (var item in clist)
                    {
                        weChat_CustomerTripRepository.Insert(new Model.Entity.WeChat.RB_WeChat_CustomerTrip()
                        {
                            Id = 0,
                            CreateBy = userInfo.Id,
                            CreateTime = DateTime.Now,
                            CustomerId = item.Id,
                            Description = Remark,
                            EmpId = 0,
                            Files = "",
                            Group_Id = userInfo.Group_Id,
                            Images = "",
                            Remark = "",
                            Status = 0,
                            Type = Common.Enum.WeChat.CustomerTripTypeEnum.Operate,
                            UpdateBy = userInfo.Id,
                            UpdateTime = DateTime.Now
                        });
                    }
                }
            }
            return flag ? "" : "出错了，请联系管理员";
        }

        /// <summary>
        /// 条件验证
        /// </summary>
        /// <param name="ConditionOk"></param>
        /// <param name="citem"></param>
        /// <param name="cvValue"></param>
        /// <returns></returns>
        private bool GetConditionValidata(bool ConditionOk, CustomerCommissionSelectModel citem, string cvValue)
        {
            switch (citem.Type)
            {
                case 1://包含
                       //方向  1包含所有/等于/等于  2包含任意/不等于/大于  3不包含/为空/大于等于  4为空/不为空/小于  5不为空/模糊/小于等于   对应 type的1/2/5
                    List<int> dxList = JsonHelper.DeserializeObject<List<int>>("[" + citem.StartValue + "]");
                    switch (citem.Direction)
                    {
                        case 1://包含所有
                            ConditionOk = true;
                            foreach (var dxitem in dxList)
                            {
                                if (!("," + cvValue + ",").Contains("," + dxitem + ","))
                                {
                                    //不包含
                                    ConditionOk = false;//此条件不成立
                                    break;
                                }
                            }
                            break;
                        case 2://包含任意
                            ConditionOk = false;
                            foreach (var dxitem in dxList)
                            {
                                if (("," + cvValue + ",").Contains("," + dxitem + ","))
                                {
                                    //包含
                                    ConditionOk = true;
                                    break;
                                }
                            }
                            break;
                        case 3://不包含
                            ConditionOk = true;
                            foreach (var dxitem in dxList)
                            {
                                if (("," + cvValue + ",").Contains("," + dxitem + ","))
                                {
                                    //包含
                                    ConditionOk = false;
                                    break;
                                }
                            }
                            break;
                        case 4://为空
                            ConditionOk = true;
                            if (!string.IsNullOrEmpty(cvValue))
                            {
                                ConditionOk = false;
                            }
                            break;
                        case 5://不为空
                            ConditionOk = true;
                            if (string.IsNullOrEmpty(cvValue))
                            {
                                ConditionOk = false;
                            }
                            break;
                    }
                    break;
                case 2://等于
                    switch (citem.Direction)
                    {
                        case 1://等于
                            ConditionOk = true;
                            if (cvValue != citem.StartValue)
                            {
                                ConditionOk = false;
                            }
                            break;
                        case 2://不等于
                            ConditionOk = true;
                            if (cvValue == citem.StartValue)
                            {
                                ConditionOk = false;
                            }
                            break;
                        case 3://为空
                            ConditionOk = true;
                            if (!string.IsNullOrEmpty(cvValue))
                            {
                                ConditionOk = false;
                            }
                            break;
                        case 4://不为空
                            ConditionOk = true;
                            if (string.IsNullOrEmpty(cvValue))
                            {
                                ConditionOk = false;
                            }
                            break;
                        case 5://模糊
                            ConditionOk = true;
                            if (!cvValue.Contains(citem.StartValue))
                            {
                                ConditionOk = false;
                            }
                            break;
                    }
                    break;
                case 3://日期
                    List<string> vList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(citem.StartValue);
                    if (string.IsNullOrEmpty(cvValue))
                    {
                        ConditionOk = false;
                    }
                    else
                    {
                        if (!vList.Contains(Convert.ToDateTime(cvValue).ToString("MM月dd号")))
                        {
                            ConditionOk = false;
                        }
                    }
                    break;
                case 4://日期范围
                    if (string.IsNullOrEmpty(cvValue))
                    {
                        ConditionOk = false;
                    }
                    else
                    {
                        if (!(Convert.ToDateTime(cvValue) >= Convert.ToDateTime(citem.StartValue) && Convert.ToDateTime(cvValue) <= Convert.ToDateTime(citem.EndValue)))
                        {
                            ConditionOk = false;
                        }
                    }
                    break;
                case 5://数值
                    switch (citem.Direction)
                    {
                        case 1://等于
                            ConditionOk = true;
                            if (Convert.ToDecimal(cvValue) != Convert.ToDecimal(citem.StartValue))
                            {
                                ConditionOk = false;
                            }
                            break;
                        case 2://大于
                            ConditionOk = true;
                            if (Convert.ToDecimal(cvValue) <= Convert.ToDecimal(citem.StartValue))
                            {
                                ConditionOk = false;
                            }
                            break;
                        case 3://大于等于
                            ConditionOk = true;
                            if (Convert.ToDecimal(cvValue) < Convert.ToDecimal(citem.StartValue))
                            {
                                ConditionOk = false;
                            }
                            break;
                        case 4://小于
                            ConditionOk = true;
                            if (Convert.ToDecimal(cvValue) >= Convert.ToDecimal(citem.StartValue))
                            {
                                ConditionOk = false;
                            }
                            break;
                        case 5://小于等于
                            ConditionOk = true;
                            if (Convert.ToDecimal(cvValue) > Convert.ToDecimal(citem.StartValue))
                            {
                                ConditionOk = false;
                            }
                            break;
                    }
                    break;
            }

            return ConditionOk;
        }

        /// <summary>
        /// 获取顺序人员ID
        /// </summary>
        /// <param name="empIdList"></param>
        /// <param name="num"></param>
        /// <returns></returns>
        private int GetRankEmpId(List<int> empIdList, int num)
        {
            int ecount = empIdList.Count();         
            if (num > ecount) {
                num %= ecount;
                if (num == 0) {
                    num = ecount;
                }
            }
            return empIdList[num - 1];
        }

        /// <summary>
        /// 获取随机人员ID
        /// </summary>
        /// <param name="empIdList"></param>
        /// <returns></returns>
        private int GetRandomEmpId(List<int> empIdList)
        {
            int ecount = empIdList.Count();
            int num = new Random().Next(1, ecount);
            return empIdList[num - 1];
        }

        /// <summary>
        /// 上传客户线索excel
        /// </summary>
        /// <param name="path_server"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public string ImportExcelForCustomerClue(string path_server, int userId)
        {
            var empModel = accountRepository.GetEmployeeInfo(userId);
            if (empModel == null) { return "用户不存在"; }
            //首先获取客户字段
            var fieldList = weChat_CustomerFieldRepository.GetList(new RB_WeChat_CustomerField_ViewModel() { Group_Id = empModel.Group_Id, Enable = 1 });
            if (!fieldList.Any()) { return "请联系管理员，客户字段不存在"; }
            foreach (var item in fieldList) {
                item.OptionsList = new List<CustomerOptions>();
                if (!string.IsNullOrEmpty(item.Options))
                {
                    item.OptionsList = JsonHelper.DeserializeObject<List<CustomerOptions>>(item.Options);
                }
            }
            List<string> fieldCList = fieldList.Select(x => x.Name).ToList();

            var list = Common.Data.QYCustomerClueHelper.GetCustomerClueData(path_server, fieldCList);
            if (list != null && list.Count > 0)
            {
                List<RB_WeChat_CustomerInfo_ViewModel> customerList = new List<RB_WeChat_CustomerInfo_ViewModel>();
                //遍历客户
                foreach (var item in list)
                {
                    if (item.list.Any())
                    {
                        //遍历客户子段
                        List<CustomFiledContentExtend> CustomFiledList = new List<CustomFiledContentExtend>();
                        string mobile = "", xName = "";
                        foreach (var qitem in item.list) {
                            var fmodel = fieldList.Where(x => x.Name == qitem.Name).FirstOrDefault();
                            if (fmodel.Required == 1 && string.IsNullOrEmpty(qitem.Value))
                            {
                                return "有必填项为空，请核实后再次上传";
                            }
                            if (fmodel.Name == "姓名")
                            {
                                xName = qitem.Value;
                            }
                            if (fmodel.Name == "电话")
                            {
                                mobile = qitem.Value;
                            }

                            switch (fmodel.Type)
                            {
                                case Common.Enum.WeChat.CustomerFieldTypeEnum.Radio:
                                    int Id = fmodel.OptionsList.Where(x => x.Name == qitem.Value).FirstOrDefault()?.Id ?? 0;
                                    CustomFiledList.Add(new CustomFiledContentExtend()
                                    {
                                        Id = fmodel.Id,
                                        Value = Id.ToString(),
                                        Name = fmodel.Name,
                                        Sort = fmodel.Sort
                                    });
                                    break;
                                case Common.Enum.WeChat.CustomerFieldTypeEnum.MultiSelect:
                                    var optionList = fmodel.OptionsList.Where(x => ("," + qitem.Value + ",").Contains("," + x.Name + ",")).ToList();
                                    CustomFiledList.Add(new CustomFiledContentExtend()
                                    {
                                        Id = fmodel.Id,
                                        Value = string.Join(",", optionList.Select(x => x.Id)),
                                        Name = fmodel.Name,
                                        Sort = fmodel.Sort
                                    });
                                    break;
                                case Common.Enum.WeChat.CustomerFieldTypeEnum.Number:
                                    CustomFiledList.Add(new CustomFiledContentExtend()
                                    {
                                        Id = fmodel.Id,
                                        Value = qitem.Value == "" ? "0" : qitem.Value,
                                        Name = fmodel.Name,
                                        Sort = fmodel.Sort
                                    });
                                    break;
                                default:
                                    CustomFiledList.Add(new CustomFiledContentExtend()
                                    {
                                        Id = fmodel.Id,
                                        Value = qitem.Value,
                                        Name = fmodel.Name,
                                        Sort = fmodel.Sort
                                    });
                                    break;
                            }
                        }

                        if (!string.IsNullOrEmpty(mobile)) {
                            #region 验证手机号码
                            bool fvalidata = weChat_CustomerInfoRepository.ValidataMobile(new RB_WeChat_CustomerInfo_ViewModel() { Group_Id = empModel.Group_Id, CustomerMobile = mobile });
                            if (fvalidata) { return xName + "手机号码已经存在"; }
                            #endregion
                        }

                        Dictionary<string, string> CustomContentKV = new Dictionary<string, string>();
                        foreach (var qitem in CustomFiledList)
                        {
                            CustomContentKV.Add("z" + qitem.Id, qitem.Value);
                        }
                        string CustomContent = JsonHelper.Serialize(CustomContentKV);
                        var demodel = new RB_WeChat_CustomerInfo_ViewModel()
                        {
                            CustomContent = JsonHelper.Serialize(CustomContentKV),
                            CustomerMobile = mobile,
                            CustomerName = xName,
                            //基本信息
                            Status = 0,
                            Group_Id = empModel.Group_Id,
                            CreateBy = empModel.Id,
                            CreateTime = DateTime.Now,
                            UpdateBy = empModel.Id,
                            UpdateTime = DateTime.Now,
                            AddWay = Common.Enum.WeChat.CustomerAddWayEnum.Person,
                            CustomerState = 2,//线索
                            ClueState = 1,//未处理
                            AllotState = 0,//分配状态
                            EmpId = 0,
                            WorkEmpId = "",
                            WorkEmpName = "",
                            ExternalUserId = "",
                            CustomerType = 1,//微信用户
                            StageId = 0,//阶段 根据领用用户来判断
                            FriendState = 2,
                        };
                        customerList.Add(demodel);
                    }
                }
                foreach (var item in customerList) {
                    weChat_CustomerInfoRepository.Insert(item);
                }
            }
            System.IO.File.Delete(path_server);
            return "";
        }

        /// <summary>
        /// 获取客户线索导入模板路径
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string GetCustomerClueExportFile(UserInfo userInfo)
        {
            var fieldList = weChat_CustomerFieldRepository.GetList(new RB_WeChat_CustomerField_ViewModel() { Group_Id = userInfo.Group_Id, Enable = 1 });
            foreach (var item in fieldList)
            {
                item.OptionsList = new List<CustomerOptions>();
                if (!string.IsNullOrEmpty(item.Options))
                {
                    item.OptionsList = JsonHelper.DeserializeObject<List<CustomerOptions>>(item.Options);
                }
            }
            fieldList = fieldList.OrderBy(x => x.Sort).ToList();
            //字段使用dataTable存储
            DataTable FieldNameList = new DataTable();
            foreach (var item in fieldList) {
                FieldNameList.Columns.Add(new DataColumn("z" + item.Id));
            }
            DataRow row = FieldNameList.NewRow();
            DataRow row1 = FieldNameList.NewRow();
            foreach (var item in fieldList)
            {
                row["z" + item.Id] = item.Name + (item.Required == 1 ? "*" : "");
                switch (item.Type) {
                    case Common.Enum.WeChat.CustomerFieldTypeEnum.Date:
                        row1["z" + item.Id] = DateTime.Now.ToString("yyyy/MM/dd");
                        break;
                    case Common.Enum.WeChat.CustomerFieldTypeEnum.MultiSelect:
                        row1["z" + item.Id] = string.Join(",", item.OptionsList.Select(x => x.Name));
                        break;
                    case Common.Enum.WeChat.CustomerFieldTypeEnum.Number:
                        row1["z" + item.Id] = "0";
                        break;
                    case Common.Enum.WeChat.CustomerFieldTypeEnum.Radio:
                        row1["z" + item.Id] = "选项值，比如 " + item.OptionsList.FirstOrDefault()?.Name ?? "";
                        break;
                    case Common.Enum.WeChat.CustomerFieldTypeEnum.Time:
                        row1["z" + item.Id] = DateTime.Now.ToString("yyyy/MM/dd HH:mm");
                        break;
                    default:
                        if (item.Name == "姓名")
                        {
                            row1["z" + item.Id] = "甲小鹤";
                        }
                        else if (item.Name == "电话")
                        {
                            row1["z" + item.Id] = "16666666666";
                        }
                        else
                        {
                            row1["z" + item.Id] = "输入文本";
                        }
                        break;
                }
            }
            FieldNameList.Rows.Add(row);
            FieldNameList.Rows.Add(row1);

            string basepath = AppContext.BaseDirectory;
            string oldPath = basepath + "\\upfile\\template\\导入线索模板.xlsx";
            string dateStr = DateTime.Now.ToString("yyyyMMdd");
            string rdStr = DateTime.Now.ToString("MMdd") + (new Random().Next(100, 999));
            string newPath = basepath + "\\upfile\\temporary\\" + dateStr + "\\导入线索模板" + rdStr + ".xlsx";
            string httpPath = "/upfile/temporary/" + dateStr + "/导入线索模板" + rdStr + ".xlsx";
            NPOIHelper.CustomerExportInsert(FieldNameList, "Sheet0", oldPath, newPath, 2);

            return httpPath;
        }
        #endregion

        #region 客户库

        /// <summary>
        /// 获取客户库查重规则
        /// </summary>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public int GetCustomerLibraryLookRepeat(int groupId)
        {
            var model = weChat_CustomerConfigRepository.GetList(new RB_WeChat_CustomerConfig_ViewModel() { Group_Id = groupId }).FirstOrDefault();
            return model?.LookRepeat ?? 1;
        }

        /// <summary>
        /// 保存客户库查重规则
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="LookRepeat"></param>
        /// <returns></returns>
        public string SetCustomerLibraryLookRepeat(int groupId, int LookRepeat) {
            var model = weChat_CustomerConfigRepository.GetList(new RB_WeChat_CustomerConfig_ViewModel() { Group_Id = groupId }).FirstOrDefault();
            if (model != null) {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerConfig_ViewModel.LookRepeat), LookRepeat}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_WeChat_CustomerConfig_ViewModel.Id),
                          FiledValue = model.Id,
                           OperatorEnum =OperatorEnum.Equal
                    }
                };
                bool flag = weChat_CustomerConfigRepository.Update(keyValues, wheres);
                return flag ? "" : "出错了，请联系管理员";
            }
            return "配置不存在";
        }

        /// <summary>
        /// 获取客户库列表
        /// </summary>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public List<RB_WeChat_CustomerLibrary_ViewModel> GetCustomerLibraryList(int group_Id)
        {
            var list = weChat_CustomerLibraryRepository.GetList(new RB_WeChat_CustomerLibrary_ViewModel() { Group_Id = group_Id });
            if (list.Any()) {
                //查询部门 人员
                string deptIds = string.Join(",", list.Where(x => !string.IsNullOrEmpty(x.DeptIds) && x.DeptIds != "-1").Select(x => x.DeptIds));
                string empIds = string.Join(",", list.Where(x => !string.IsNullOrEmpty(x.EmpIds) && x.EmpIds != "-1").Select(x => x.EmpIds));

                foreach (var item in list) {
                    item.LimitList = new List<PrivateLibraryLimitExtend>();
                    if (!string.IsNullOrEmpty(item.PrivateLibraryLimit))
                    {
                        item.LimitList = JsonHelper.DeserializeObject<List<PrivateLibraryLimitExtend>>(item.PrivateLibraryLimit);
                        string dIds = string.Join(",", item.LimitList.Where(x => !string.IsNullOrEmpty(x.DeptIds) && x.DeptIds != "-1").Select(x => x.DeptIds));
                        string eIds = string.Join(",", item.LimitList.Where(x => !string.IsNullOrEmpty(x.EmpIds) && x.EmpIds != "-1").Select(x => x.EmpIds));
                        if (!string.IsNullOrEmpty(dIds)) {
                            if (!string.IsNullOrEmpty(deptIds))
                            {
                                deptIds += "," + dIds;
                            }
                            else {
                                deptIds = dIds;
                            }
                        }
                        if (!string.IsNullOrEmpty(eIds)) {
                            if (!string.IsNullOrEmpty(empIds))
                            {
                                empIds += "," + eIds;
                            }
                            else
                            {
                                empIds = eIds;
                            }
                        }
                    }
                }

                List<RB_Department_ViewModel> deptList = new List<RB_Department_ViewModel>();
                if (!string.IsNullOrEmpty(deptIds))
                {
                    deptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = group_Id, QDeptIds = deptIds });
                }
                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(empIds))
                {
                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = group_Id, QIds = empIds });
                }

                foreach (var item in list) {
                    item.DeptList = new List<RB_Department_ViewModel>();
                    item.EmpList = new List<Employee_ViewModel>();
                    if (!string.IsNullOrEmpty(item.DeptIds) && item.DeptIds != "-1")
                    {
                        item.DeptList = deptList.Where(x => ("," + item.DeptIds + ",").Contains("," + x.DeptId + ",")).ToList();
                    }
                    if (!string.IsNullOrEmpty(item.EmpIds) && item.EmpIds != "-1")
                    {
                        item.EmpList = empList.Where(x => ("," + item.EmpIds + ",").Contains("," + x.Id + ",")).ToList();
                    }

                    item.ConditionList = new List<RecycleConditionModel>();
                    if (!string.IsNullOrEmpty(item.RecycleCondition)) {
                        item.ConditionList = JsonHelper.DeserializeObject<List<RecycleConditionModel>>(item.RecycleCondition);
                    }

                    foreach (var qitem in item.LimitList) {
                        qitem.DeptList = new List<RB_Department_ViewModel>();
                        qitem.EmpList = new List<Employee_ViewModel>();
                        if (!string.IsNullOrEmpty(qitem.DeptIds) && qitem.DeptIds != "-1")
                        {
                            qitem.DeptList = deptList.Where(x => ("," + qitem.DeptIds + ",").Contains("," + x.DeptId + ",")).ToList();
                        }
                        if (!string.IsNullOrEmpty(qitem.EmpIds) && qitem.EmpIds != "-1")
                        {
                            qitem.EmpList = empList.Where(x => ("," + qitem.EmpIds + ",").Contains("," + x.Id + ",")).ToList();
                        }
                    }

                    item.PrivateLibraryTypeStr = "";
                    if (!string.IsNullOrEmpty(item.PrivateLibraryType)) {
                        List<int> typeIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.PrivateLibraryType + "]");
                        foreach (var typeId in typeIdList)
                        {
                            item.PrivateLibraryTypeStr += ((Common.Enum.WeChat.CustomerAddWayEnum)typeId).ToName() + "、";
                        }
                        item.PrivateLibraryTypeStr = item.PrivateLibraryTypeStr[0..^1];
                    }

                    item.NotRecycleTimeList = new List<NotRecycleTimeModel>();
                    if (!string.IsNullOrEmpty(item.NotRecycleTime)) {
                        item.NotRecycleTimeList = JsonHelper.DeserializeObject<List<NotRecycleTimeModel>>(item.NotRecycleTime);
                    }
                }

            }
            return list;
        }

        /// <summary>
        /// 获取客户库详情
        /// </summary>
        /// <param name="libraryId"></param>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public RB_WeChat_CustomerLibrary_ViewModel GetCustomerLibraryInfo(int libraryId,int group_Id)
        {
            var list = weChat_CustomerLibraryRepository.GetList(new RB_WeChat_CustomerLibrary_ViewModel() { Group_Id = group_Id, Id = libraryId });
            if (list.Any())
            {
                //查询部门 人员
                string deptIds = string.Join(",", list.Where(x => !string.IsNullOrEmpty(x.DeptIds) && x.DeptIds != "-1").Select(x => x.DeptIds));
                string empIds = string.Join(",", list.Where(x => !string.IsNullOrEmpty(x.EmpIds) && x.EmpIds != "-1").Select(x => x.EmpIds));

                foreach (var item in list)
                {
                    item.LimitList = new List<PrivateLibraryLimitExtend>();
                    if (!string.IsNullOrEmpty(item.PrivateLibraryLimit))
                    {
                        item.LimitList = JsonHelper.DeserializeObject<List<PrivateLibraryLimitExtend>>(item.PrivateLibraryLimit);
                        string dIds = string.Join(",", item.LimitList.Where(x => !string.IsNullOrEmpty(x.DeptIds) && x.DeptIds != "-1").Select(x => x.DeptIds));
                        string eIds = string.Join(",", item.LimitList.Where(x => !string.IsNullOrEmpty(x.EmpIds) && x.EmpIds != "-1").Select(x => x.EmpIds));
                        if (!string.IsNullOrEmpty(dIds))
                        {
                            if (!string.IsNullOrEmpty(deptIds))
                            {
                                deptIds += "," + dIds;
                            }
                            else
                            {
                                deptIds = dIds;
                            }
                        }
                        if (!string.IsNullOrEmpty(eIds))
                        {
                            if (!string.IsNullOrEmpty(empIds))
                            {
                                empIds += "," + eIds;
                            }
                            else
                            {
                                empIds = eIds;
                            }
                        }
                    }
                }

                List<RB_Department_ViewModel> deptList = new List<RB_Department_ViewModel>();
                if (!string.IsNullOrEmpty(deptIds))
                {
                    deptList = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = group_Id, QDeptIds = deptIds });
                }
                List<Employee_ViewModel> empList = new List<Employee_ViewModel>();
                if (!string.IsNullOrEmpty(empIds))
                {
                    empList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = group_Id, QIds = empIds });
                }

                foreach (var item in list)
                {
                    item.DeptList = new List<RB_Department_ViewModel>();
                    item.EmpList = new List<Employee_ViewModel>();
                    if (!string.IsNullOrEmpty(item.DeptIds) && item.DeptIds != "-1")
                    {
                        item.DeptList = deptList.Where(x => ("," + item.DeptIds + ",").Contains("," + x.DeptId + ",")).ToList();
                    }
                    if (!string.IsNullOrEmpty(item.EmpIds) && item.EmpIds != "-1")
                    {
                        item.EmpList = empList.Where(x => ("," + item.EmpIds + ",").Contains("," + x.Id + ",")).ToList();
                    }

                    item.ConditionList = new List<RecycleConditionModel>();
                    if (!string.IsNullOrEmpty(item.RecycleCondition))
                    {
                        item.ConditionList = JsonHelper.DeserializeObject<List<RecycleConditionModel>>(item.RecycleCondition);
                    }

                    foreach (var qitem in item.LimitList)
                    {
                        qitem.DeptList = new List<RB_Department_ViewModel>();
                        qitem.EmpList = new List<Employee_ViewModel>();
                        if (!string.IsNullOrEmpty(qitem.DeptIds) && qitem.DeptIds != "-1")
                        {
                            qitem.DeptList = deptList.Where(x => ("," + qitem.DeptIds + ",").Contains("," + x.DeptId + ",")).ToList();
                        }
                        if (!string.IsNullOrEmpty(qitem.EmpIds) && qitem.EmpIds != "-1")
                        {
                            qitem.EmpList = empList.Where(x => ("," + qitem.EmpIds + ",").Contains("," + x.Id + ",")).ToList();
                        }
                    }

                    item.PrivateLibraryTypeStr = "";
                    if (!string.IsNullOrEmpty(item.PrivateLibraryType))
                    {
                        List<int> typeIdList = JsonHelper.DeserializeObject<List<int>>("[" + item.PrivateLibraryType + "]");
                        foreach (var typeId in typeIdList)
                        {
                            item.PrivateLibraryTypeStr += ((Common.Enum.WeChat.CustomerAddWayEnum)typeId).ToName() + "、";
                        }
                        item.PrivateLibraryTypeStr = item.PrivateLibraryTypeStr[0..^1];
                    }

                    item.NotRecycleTimeList = new List<NotRecycleTimeModel>();
                    if (!string.IsNullOrEmpty(item.NotRecycleTime))
                    {
                        item.NotRecycleTimeList = JsonHelper.DeserializeObject<List<NotRecycleTimeModel>>(item.NotRecycleTime);
                    }
                }
            }
            return list.FirstOrDefault();
        }

        /// <summary>
        /// 新增修改客户库
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetCustomerLibraryInfo(RB_WeChat_CustomerLibrary_ViewModel demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.Name), demodel.Name},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.IsAllowRepeat), demodel.IsAllowRepeat},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.DeptIds), demodel.DeptIds},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.EmpIds), demodel.EmpIds},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.RecyclingType), demodel.RecyclingType},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.RecycleCondition), demodel.RecycleCondition},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.NotRecycleTime), demodel.NotRecycleTime},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.RemindDay), demodel.RemindDay},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.RemindType), demodel.RemindType},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.LimitDay), demodel.LimitDay},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.PrivateLibraryLimit), demodel.PrivateLibraryLimit},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.PrivateLibraryType), demodel.PrivateLibraryType},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_WeChat_CustomerLibrary_ViewModel.UpdateTime), demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_WeChat_CustomerLibrary_ViewModel.Id),
                          FiledValue = demodel.Id,
                           OperatorEnum =OperatorEnum.Equal
                    }
                };
                bool flag = weChat_CustomerLibraryRepository.Update(keyValues, wheres);
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                bool flag = weChat_CustomerLibraryRepository.Insert(demodel) > 0;
                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_CustomerInfo_ViewModel> GetCustomerRepeatToFollowUpPageList(int pageIndex, int pageSize, out long count, RB_WeChat_CustomerInfo_ViewModel demodel)
        {
            if (!string.IsNullOrEmpty(demodel.CName))
            {
                //查询姓名的自定义ID
                demodel.CNameId = weChat_CustomerFieldRepository.GetList(new RB_WeChat_CustomerField_ViewModel() { Group_Id = demodel.Group_Id, CName = "姓名" }).FirstOrDefault()?.Id ?? 0;
                if (demodel.CNameId <= 0)
                {
                    count = 0;
                    return new List<RB_WeChat_CustomerInfo_ViewModel>();
                }
            }
            var RList = new List<RB_WeChat_CustomerInfo_ViewModel>();
            var clist = weChat_CustomerInfoRepository.GetCustomerRepeatToFollowUpPageList(pageIndex, pageSize, out count, demodel);
            if (clist.Any()) {
                //根据客人的企业微信ID  查询出所有的客户ID
                string ExternalUserIds = "'" + string.Join("','", clist.Select(x => x.ExternalUserId)) + "'";
                var list = weChat_CustomerInfoRepository.GetList(new RB_WeChat_CustomerInfo_ViewModel() { Group_Id = demodel.Group_Id, Q_ExternalUserIds = ExternalUserIds });
                if (list.Any()) {
                    //客户标签
                    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 stageIds = string.Join(",", list.Where(x => x.StageId > 0).Select(x => x.StageId));
                    List<RB_WeChat_CustomerStage_ViewModel> StageList = new List<RB_WeChat_CustomerStage_ViewModel>();
                    if (!string.IsNullOrEmpty(stageIds))
                    {
                        StageList = weChat_CustomerStageRepository.GetList(new RB_WeChat_CustomerStage_ViewModel() { Group_Id = demodel.Group_Id, StageIds = stageIds });
                    }
                    //负责人 、 公海前负责人查询
                    List<Employee_ViewModel> EmpList = new List<Employee_ViewModel>();
                    string EmpWorkUserId = "'" + string.Join("','", list.Where(x => !string.IsNullOrEmpty(x.WorkEmpId)).Select(x => x.WorkEmpId).Distinct()) + "'";
                    if (EmpWorkUserId != "''")
                    {
                        EmpList = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = demodel.Group_Id, WorkUserIds = EmpWorkUserId });
                    }
                   
                    //自定义字段  -- 这个怎么处理呢  根据自定义子段遍历吗
                    //先直接返回自定义子段
                    var cFieldList = weChat_CustomerFieldRepository.GetList(new RB_WeChat_CustomerField_ViewModel() { Group_Id = demodel.Group_Id, Enable = 1 });
                    foreach (var item in cFieldList)
                    {
                        item.OptionsList = new List<CustomerOptions>();
                        if (!string.IsNullOrEmpty(item.Options))
                        {
                            item.OptionsList = JsonHelper.DeserializeObject<List<CustomerOptions>>(item.Options);
                        }
                    }

                    foreach (var item in list)
                    {
                        item.LableList = LableList.Where(x => ("," + x.LableIds + ",").Contains("," + x.Id + ",")).ToList();
                        item.StageName = StageList.Where(x => x.Id == item.StageId).FirstOrDefault()?.Name ?? "";
                        if (demodel.CustomerState == 3)
                        {
                            item.OldEmpName = EmpList.Where(x => x.Id == item.OldEmpId).FirstOrDefault()?.EmployeeName ?? "";
                        }
                        else
                        {
                            var empModel = EmpList.Where(x => x.WorkUserId == item.WorkEmpId).FirstOrDefault();
                            item.EmpId = empModel?.Id ?? 0;
                            item.EmpName = (empModel?.EmployeeName ?? "") + ((empModel?.IsLeave ?? 0) == 2 ? "(已离职)" : "");
                        }

                        List<CustomerFiledContentModel> CustomValueList = new List<CustomerFiledContentModel>();
                        if (!string.IsNullOrEmpty(item.CustomContent))
                        {
                            var keyValueList = JsonHelper.DeserializeObject<Dictionary<string, string>>(item.CustomContent);
                            foreach (var kitem in keyValueList)
                            {
                                CustomValueList.Add(new CustomerFiledContentModel
                                {
                                    Id = Convert.ToInt32(kitem.Key.Replace("z", "")),
                                    Value = kitem.Value
                                });
                            }
                        }

                        item.CustomFiledList = new List<CustomFiledContentExtend>();
                        foreach (var qitem in cFieldList)
                        {
                            var cmodel = CustomValueList.Where(x => x.Id == qitem.Id).FirstOrDefault();
                            string value = cmodel?.Value ?? "";
                            if (qitem.Type == Common.Enum.WeChat.CustomerFieldTypeEnum.Date)
                            {
                                item.CustomFiledList.Add(new CustomFiledContentExtend()
                                {
                                    Id = qitem.Id,
                                    Value = value,
                                    ShowValue = value != "" ? Convert.ToDateTime(value).ToString("yyyy-MM-dd") : "",
                                    Name = qitem.Name,
                                    Sort = qitem.Sort
                                });
                            }
                            else if (qitem.Type == Common.Enum.WeChat.CustomerFieldTypeEnum.MultiSelect)
                            {
                                var optionList = qitem.OptionsList.Where(x => ("," + value + ",").Contains("," + x.Id + ",")).ToList();
                                item.CustomFiledList.Add(new CustomFiledContentExtend()
                                {
                                    Id = qitem.Id,
                                    ShowValue = string.Join(",", optionList.Select(x => x.Name)),
                                    Value = string.Join(",", optionList.Select(x => x.Id)),
                                    Name = qitem.Name,
                                    Sort = qitem.Sort
                                });
                            }
                            else if (qitem.Type == Common.Enum.WeChat.CustomerFieldTypeEnum.Radio)
                            {
                                int vInt = Convert.ToInt32(value == "" ? "0" : value);
                                var Name = qitem.OptionsList.Where(x => x.Id == vInt).FirstOrDefault()?.Name ?? "";
                                item.CustomFiledList.Add(new CustomFiledContentExtend()
                                {
                                    Id = qitem.Id,
                                    ShowValue = Name,
                                    Value = value,
                                    Name = qitem.Name,
                                    Sort = qitem.Sort
                                });
                            }
                            else if (qitem.Type == Common.Enum.WeChat.CustomerFieldTypeEnum.Time)
                            {
                                item.CustomFiledList.Add(new CustomFiledContentExtend()
                                {
                                    Id = qitem.Id,
                                    ShowValue = value != "" ? Convert.ToDateTime(value).ToString("yyyy-MM-dd HH:mm") : "",
                                    Value = value,
                                    Name = qitem.Name,
                                    Sort = qitem.Sort
                                });
                            }
                            else
                            {
                                item.CustomFiledList.Add(new CustomFiledContentExtend()
                                {
                                    Id = qitem.Id,
                                    ShowValue = value,
                                    Value = value,
                                    Name = qitem.Name,
                                    Sort = qitem.Sort
                                });
                            }
                        }
                    }
                }
                foreach (var item in clist)
                {
                    RList.AddRange(list.Where(x => x.ExternalUserId == item.ExternalUserId).ToList());
                }
            }
            return RList;
        }

        #endregion

        #region 自定义查询

        /// <summary>
        /// 保存查询条件
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SaveCustomQuery(RB_CustomQuery model)
        {
            if (model.Id == 0)
            {
                return customQueryRepository.Insert(model) > 0;
            }
            else 
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_CustomQuery.Name), model.Name},
                    { nameof(RB_CustomQuery.SelectList), model.SelectList},
                    { nameof(RB_CustomQuery.AddCondition), model.AddCondition}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName= nameof(RB_CustomQuery.Id),
                          FiledValue= model.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return customQueryRepository.Update(keyValues, wheres);
            }
        }

        /// <summary>
        /// 物理删除指定的查询条件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteCustomQuery(int id,int uid)
        {
            List<WhereHelper> whereHelpers = new List<WhereHelper>();
            whereHelpers.Add(new WhereHelper() { 
                FiledName=nameof(RB_CustomQuery.Id),
                FiledValue= id,
                OperatorEnum=OperatorEnum.Equal
            });
            whereHelpers.Add(new WhereHelper()
            {
                FiledName = nameof(RB_CustomQuery.CreateBy),
                FiledValue = uid,
                OperatorEnum = OperatorEnum.Equal
            });
            return customQueryRepository.Delete(whereHelpers);
        }

        /// <summary>
        /// 查询用户所有的自定义查询信息
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public object GetUserCustomQuery(int uid,string code)
        {
            var list = customQueryRepository.GetUserCustomQuery(uid,code);
            object result = null;
            if (list != null && list.Count>0) 
            {
                result = list.Select(x => new { 
                    x.Id,
                    x.Name
                }).ToList();
            }
            return result;
        }

        /// <summary>
        /// 查询指定ID的查询条件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public RB_CustomQuery GetCustomQueryById(int id, int uid)
        {

            var model = customQueryRepository.GetEntity(id);
            RB_CustomQuery result = null;

            if (model != null && model.Id == id && model.CreateBy == uid)
            {
                result = model;
            }

            return result;
        }

        #endregion
    }
}

