using CRM.Core.DTO;
using CRM.Core.DTO.Ord;
using CRM.Core.DTO.Res;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using WX.CRM.BLL.Base;
using WX.CRM.BLL.Csvr;
using WX.CRM.BLL.Level2;
using WX.CRM.BLL.Res;
using WX.CRM.BLL.Util;
using WX.CRM.Common;
using WX.CRM.Common.Employee;
using WX.CRM.IBLL.Util;
using WX.CRM.Model.Entity;
using WX.CRM.Model.Enum;
namespace WX.CRM.BLL.Soft
{
///
/// 抓取接口数据,旧系统为JMDUSER
///
public class GET_REGUSER
{
private CACHE_BL cacheQ = new CACHE_BL();
//RES_ACTIVITY_BL _resActivityQ = new RES_ACTIVITY_BL();
private CSVR_FAVORITECUSTOMER_BL _favCustomerQ = new CSVR_FAVORITECUSTOMER_BL();
private CSVR_TODOITEM_BL _todoItem = new CSVR_TODOITEM_BL();
//RES_DISTRIBUTE_DETAIL_BL _resDistributeDetial = new RES_DISTRIBUTE_DETAIL_BL();
private RES_APPLY_BL _apply = new RES_APPLY_BL();
private RES_MYALLOCATERES_BL _resMyAllocateRes = new RES_MYALLOCATERES_BL();
private BAS_INNERUSER_BL _user = new BAS_INNERUSER_BL();
private BAS_PARAMETER_BL _para = new BAS_PARAMETER_BL();
private RES_CUSTOMER_BL customer_bl = new RES_CUSTOMER_BL();
private RES_CUSTOMERUSER_BL customeruser_q = new RES_CUSTOMERUSER_BL();
private SOFT_USER_BL softUser_bl = new SOFT_USER_BL();
private ISecurityHelper sHelper = new SecurityHelper();
private L2_SOFT_ORDER_BL _order = new L2_SOFT_ORDER_BL();
private RES_RESOURCEMOBILE_BL _RES_RESOURCEMOBILE_Q = new RES_RESOURCEMOBILE_BL();
/*接口返回的字符串:18696548545,5001,6201075,5001,2013-8-7 13:54:16【手机号,标签,卡号,用户名,注册时间】*/
///
/// 从接口抓取到的注册用户,旧系统名称为jmdUser
///
/// 手机号
/// 注册标签
/// 卡号
/// 用户名
/// 注册时间
public void RegUser(string mobile, string tag, string cardNo, string userName, DateTime? regDate, int companyId, string activeMobile = null, string platform = null, string jsonData = null, string dataType = null, string extXML = null, string kWord = null, string eid = null, string openid = null, string openplat = null, string unionid = null, string liveCode = null, string regSource = null, string refeid = null, int? sgid = null, SyncRegExtraModel extraModel = null)
{
ValidationErrors errors = new ValidationErrors();
try
{
string liveCodeStr = "";
var userList = cacheQ.GetUserList();
var pici = new SEQUENCES_BL().Seq_base_get();
var v_resid = string.Empty;
var v_umid = string.Empty;
if (!string.IsNullOrEmpty(mobile))
{
v_resid = ResUtil.CreateResId(mobile);
if (string.IsNullOrWhiteSpace(extraModel.umid))
{
extraModel.umid = cacheQ.GetUMid(mobile);
}
new BLL.Res.RES_CUSTOMER_BL().ResgisterCustomer(mobile, v_resid, tag, v_umid: extraModel.umid);
}
var deptid = 0;
if (extraModel != null)
{
if (extraModel.deptId.HasValue && extraModel.deptId > 0)
{
deptid = extraModel.deptId.Value;
}
if (extraModel.ch.HasValue && extraModel.ch > 0)
{
deptid = BuildDeptIdByResId(resId: v_resid, ch: extraModel.ch);
}
}
using (var db = new crmContext())
{
//注册customer
var regUser = db.SOFT_USER.FirstOrDefault(p => p.USERNAME == userName);
if (regUser == null)
{
var softUser = new SOFT_USER();
softUser.USERNAME = userName;
softUser.USERPASS = "string.Empty";
if (!string.IsNullOrEmpty(cardNo))
softUser.USERNO = decimal.Parse(cardNo);
softUser.CTIME = System.DateTime.Now;
softUser.COMPANYID = companyId;
softUser.UMID = v_umid;
softUser.REGCAMPAINID = Convert.ToInt32(tag);
softUser.REGDATE = regDate;
softUser.RESID = v_resid;
softUser.REGPLATFORM = platform ?? "0";
softUser.OPENID = openid;//***第三方用户ID***
softUser.OPENPLAT = openplat;//***第三方平台***
if (!string.IsNullOrWhiteSpace(refeid))
{
softUser.EID = Convert.ToInt32(refeid);
eid = refeid;
}
if (!string.IsNullOrEmpty(activeMobile))
{
softUser.ISACTIVE = 1;
softUser.ACTIVERESID = v_resid;
softUser.ACTIVETIME = regDate;
}
if (!string.IsNullOrEmpty(unionid))
softUser.UNIONID = unionid;
softUser.LIVECODE = liveCode;
softUser.REGSOURCE = regSource;
db.SOFT_USER.Add(softUser);
#region 新用户免费赠送产品
try
{
var productJson = db.BAS_PARAMETER.FirstOrDefault(m => m.PARAKEY.Trim().ToLower() == "register_for_complimentary_products");
var ch = Convert.ToInt32(tag);
if (productJson != null && !string.IsNullOrEmpty(productJson.PARAVALUE))
{
var c_produts = Newtonsoft.Json.JsonConvert.DeserializeObject>(productJson.PARAVALUE);
foreach (var item in c_produts)
{
if (item.max_ch >= ch && item.min_ch <= ch)
{ //渠道赛选
foreach (var pro in item.product)
{
var product = cacheQ.GetSProductList().Where(p => p.PRODUCTCODE == pro.pcode).FirstOrDefault();
if (product != null)
{
//创建免费订单
decimal orderId = 0;
bool result = _order.CreateOrder(product.PRODUCTID, product.PRODUCTCODE, v_resid, userName, companyId, 0, 1, pro.days, product.PRICE ?? 0, out orderId, null, item.deptcode);
if (result)
{
#region 开通订单
var autoOpenFreeOrder = cacheQ.GetValue_Parameter("AutoOpenFreeOrder");
if (string.IsNullOrEmpty(autoOpenFreeOrder) || autoOpenFreeOrder == "true")
{
var freeOrderRule = cacheQ.GetValue_Parameter("FreeOrderRule");
if (string.IsNullOrEmpty(freeOrderRule))
{
OpenOrder(orderId.ToString(), "新用户自动申请开通", companyId, 0);
continue;
}
var rule = Newtonsoft.Json.JsonConvert.DeserializeObject(freeOrderRule);
//查看是否有规则,如果没有直接开通
if (rule.IsLimit)
{
var productRule = rule.Products.FirstOrDefault(p => p.ProductId == product.PRODUCTID);
if (productRule != null)
{
var freeOrderList = _order.getOrderByResId(v_resid, product.PRODUCTID);
var hasOrderCount = freeOrderList.Count;
if (hasOrderCount >= productRule.Limit)
{
LogHelper.Info("新用户免费赠送下单成功,请联系总监助理,手工开通!");
}
else
{
OpenOrder(orderId.ToString(), "新用户自动申请开通", companyId, 0);
}
}
else
{
OpenOrder(orderId.ToString(), "新用户自动申请开通", companyId, 0);
}
}
else
{
OpenOrder(orderId.ToString(), "新用户自动申请开通", companyId, 0);
}
}
else
{
LogHelper.Info("新用户免费赠送下单成功,请联系总部开通!");
}
#endregion 开通订单
//日志
}
else
{
//日志
LogHelper.Info("免费订单赠送失败:" + Newtonsoft.Json.JsonConvert.SerializeObject(new
{
product.PRODUCTID,
product.PRODUCTCODE,
v_resid,
userName,
companyId,
salesid = 0,
ordertype = 1,
pro.days,
price = product.PRICE ?? 0,
mainOrderId = "",
item.deptcode
}));
}
}
}
}
}
}
}
catch (Exception ex)
{ //日志
LogHelper.Info("免费订单赠送失败:" + ex.Message + ex.StackTrace);
}
#endregion 新用户免费赠送产品
liveCodeStr = string.IsNullOrEmpty(softUser.LIVECODE) ? "" : softUser.LIVECODE;
}
else
{
if (!string.IsNullOrWhiteSpace(refeid))
{
regUser.EID = Convert.ToInt32(refeid);
}
if (!string.IsNullOrEmpty(unionid))
{
regUser.UNIONID = unionid;
}
if (string.IsNullOrWhiteSpace(regUser.RESID))
{
regUser.RESID = v_resid;
}
if (string.IsNullOrWhiteSpace(regUser.UMID))
{
regUser.UMID = v_umid;
}
liveCodeStr = string.IsNullOrEmpty(regUser.LIVECODE) ? "" : regUser.LIVECODE;
//LogHelper.Info("regUser.EID:" + regUser.EID.ToString() + ",regUser.UNIONID:" + regUser.UNIONID);
}
//liveCode 为"wxh5reg_"开头的为企业微信邀请注册,目前这种不做任何分配调用
//根据渠道获取事业线
//分配EID不是空的,直接分配资源
if (!string.IsNullOrWhiteSpace(eid) && !string.IsNullOrEmpty(v_resid))
{
//优先根据工号
var eid32 = Convert.ToInt32(eid);
//var user = userList.FirstOrDefault(p => p.EID == eid32);
var user = _user.getInnerUserByEid(eid32);
if (user != null && user.DEPTID > 0)
{
deptid = user.DEPTID.Value;
}
var isExe = false;
var myRes = db.RES_MYALLOCATERES.FirstOrDefault(p => p.RESID == v_resid);
if (deptid > 0)
{
myRes = db.RES_MYALLOCATERES.FirstOrDefault(p => p.RESID == v_resid && p.DEPTID == deptid);
}
var para = _para.GetModel_Patameter("IgnoreManager");
if (para != null && myRes != null)
{
var manager = _user.GetModel(myRes.INNERUSERID);
if (!string.IsNullOrEmpty(para.PARAVALUE))
{
var manageList = para.PARAVALUE.Split(',');
foreach (var item in manageList)
{
if (item == manager.EID.ToString())
{
isExe = true;
}
}
}
}
//如果不存在分配关系,才需要分配
if (myRes == null || isExe)
{
if (user != null)
{
var info = new RES_ALLCOTE_USER()
{
ID = new SEQUENCES_BL().Seq_base_get(),
INNERUSERID = user.PKID,
EID = eid32,
NUM = 1,
CTIME = DateTime.Now,
PICI = pici,
RESID = v_resid,
TYPE = 1,
DEPTID = deptid
};
if (sgid.HasValue)
{
info.SGID = sgid.Value;
}
db.RES_ALLCOTE_USER.Add(info);
}
}
}
db.SaveChanges();
}
//资源绑定关系
if (!string.IsNullOrEmpty(v_resid))
{
new BLL.Res.RES_CUSTOMERUSER_BL().ContractUser(v_resid, userName);
}
//资源分配关系,资源兜底
//企业微信注册邀请不需要兜底 wxh5reg_
if (!liveCodeStr.StartsWith("wxh5reg_") && !liveCodeStr.StartsWith("wssc_") && !string.IsNullOrWhiteSpace(eid) && !string.IsNullOrEmpty(v_resid))
{
var eid1000 = userList.FirstOrDefault(p => p.EID == 10000).PKID;
_resMyAllocateRes.ExeSeniorDistributeByResId(eid1000, pici, "扫码直接分配");
}
//进入资源流程
if (!string.IsNullOrEmpty(mobile))
{
ImportResApply(mobile, tag, cardNo, userName, regDate, deptid: deptid);
}
#region 提醒
if (!string.IsNullOrEmpty(v_resid))
{
try
{
var user10000 = cacheQ.GetUserList().Find(p => p.EID == 10000).PKID;
var favCustomer = _favCustomerQ.GetModel_FavoriteCustomer(v_resid, null);
if (favCustomer != null)
{
//说明这个用户有人收藏,提醒业务员
var todoItem = new CSVR_TODOITEM()
{
PKID = new SEQUENCES_BL().Seq_base_get(),
SENDEDUSERID = user10000,
RECEIVEDUSERID = favCustomer.SALESID,
ISPRIVATE = 1,
RESID = v_resid,
MEMO = "您收藏的客户注册了",
STARTTIME = DateTime.Now,
URL = "/Csvr/CustomerInfo/CustomerDetail?resid=" + v_resid,
URLTITLE = "客户详细"
};
_todoItem.Create(ref errors, todoItem);
LogHelper.Info(todoItem.ToJson());
}
}
catch (Exception exx)
{
LogHelper.Error(exx.ToString());
}
}
#endregion 提醒
}
catch (System.Data.Entity.Validation.DbEntityValidationException exception)
{
var errorMessages =
exception.EntityValidationErrors
.SelectMany(validationResult => validationResult.ValidationErrors)
.Select(m => m.ErrorMessage);
var fullErrorMessage = string.Join(", ", errorMessages);
//记录日志
//Log.Error(fullErrorMessage);
var exceptionMessage = string.Concat(exception.Message, " 验证异常消息是:", fullErrorMessage);
LogHelper.Error(exceptionMessage);
throw new System.Data.Entity.Validation.DbEntityValidationException(exceptionMessage, exception.EntityValidationErrors);
}
catch
{
throw;
}
}
private bool OpenOrder(string id, string reson, decimal companyId, decimal UserId)
{
L2_SOFT_ORDER model = null;
string AdminPassword = cacheQ.GetValue_Parameter(Parameter.ISVR_CN_JMDAgentPwd);
string AdminAgentId = cacheQ.GetValue_Parameter(Parameter.ISVR_CN_JMDAgentId);
string url = "";
string json = "";
if (!string.IsNullOrEmpty(id))
{
decimal orderId = Convert.ToDecimal(id);
model = _order.getOrderByOrderId(orderId);
}
var product = cacheQ.GetSProductList().Where(p => p.PRODUCTID == model.PRODUCTID).FirstOrDefault();
freeordermodel theModel = new freeordermodel();
PhoneLogModel phoneLogModel = new PhoneLogModel
{
Method = System.Reflection.MethodBase.GetCurrentMethod().Name,
userid = UserId
};
theModel.mobile = _RES_RESOURCEMOBILE_Q.GetNumberByResId(model.RESID, phoneLogModel);
theModel.needpay = model.PRICE;
theModel.opendays = 1;
theModel.ordertype = 1;
theModel.productId = model.PRODUCTID;
theModel.remark = reson;
theModel.saledeptid = companyId;
theModel.source = "1";
theModel.softusername = model.USERNAME;
theModel.productcode = model.PRODUCTCODE;//小类代码
theModel.teamserve = 1;
theModel.userid = model.CREATEUSER;
theModel.count = Convert.ToInt32(model.DAYS);//产品数 --免费产品始终一天,这里天数作为数量传递,达到天数效果
theModel.productType = Convert.ToInt32(product.PRODUCTTYPE);//产品分类
theModel.opuser = UserId;
theModel.ctime = DateTimeTool.ConvertDateTimeInt(model.CTIME).ToString();
//theModel.companycode = companyCode;
theModel.companycode = Utility.GetSettingOrNullByKey("DataClientCode");
theModel.days = Convert.ToInt32(model.DAYS);
theModel.mainOrderId = model.MAINORDERID.HasValue ? Convert.ToInt32(model.MAINORDERID) : (int?)null;
var depment = cacheQ.GetList_SalesDepartMent();
if (!string.IsNullOrEmpty(model.DEPTCODE))
{
var dep = depment.Find(p => p.SALEDEPTCODE == model.DEPTCODE);
if (dep != null)
{
if (dep.CHANNELDEF.HasValue)
theModel.ch = (int)dep.CHANNELDEF;
}
}
url = cacheQ.GetValue_Parameter(Parameter.Core_ZxdService_FreeOrder);//内部接口··开通免费订单接口
json = Utility.ConvertToJSON(theModel);
json = sHelper.createSignEncodingStr(json, SecurityHelper.OrderClientIdKey);
LogHelper.Info("投顾订单" + model.ORDERID + (string.IsNullOrEmpty(model.WEBORDERID) ? "" : string.Format("({0})", model.WEBORDERID)) + "审核:" + url + "?" + json);
string retmsg = Utility.PostData(url + "?" + json, Encoding.UTF8);
retmsg = sHelper.decyptData(SecurityHelper.OrderClientIdKey, retmsg);
CreateOrderRsp retmessage = Newtonsoft.Json.JsonConvert.DeserializeObject(retmsg);//返回信息
if (retmessage.retCode == (int)NodeJsOrderEnum.调用成功)//成功
{
ValidationErrors errors = new ValidationErrors();
model.ORDERSTATUS = 1;
model.OPENUSER = UserId;
model.OTIME = DateTime.Now;
model.WEBORDERID = retmessage.orderId;
model.MEMO = reson;
_order.UpdateOrder(ref errors, model);
//日志
LogHelper.Info("免费订单自动赠送成功:" + Newtonsoft.Json.JsonConvert.SerializeObject(new
{
errors
}));
return true;
}
else
{
//日志
LogHelper.Info("免费订单自动赠送失败:" + Newtonsoft.Json.JsonConvert.SerializeObject(new
{
retmessage
}));
return false;
}
}
public retMsgNew> GetUserByZXD(string resId, string companyCode, decimal eid, List deptids)
{
if (string.IsNullOrWhiteSpace(companyCode))
{
companyCode = Utility.GetSettingOrNullByKey("DataClientCode");
}
var customer = customer_bl.getResCustomerByResId(resId);
var list = customeruser_q.GetListByCustomerId(customer?.CUSTOMERID);
if (list.Count() > 0)
{
resId = string.Join(",", list.Select(n => n.RESID).Distinct());
}
var softuser = softUser_bl.GetUserList_userName(list.Select(m => m.USERNAME).ToArray());
var softName = "";
if (softuser.Count() > 0)
{
softName = string.Join(",", softuser.Select(m => m.USERNAME));
}
var url = cacheQ.GetValue_Parameter(Parameter.Core_ZxdService_GetOtherUser);
var theModel = new Soft_User_GetCheckDTO() { companyCode = companyCode, eid = Convert.ToInt32(eid), resid = resId, softusername = softName, deptids = deptids };
string json = Newtonsoft.Json.JsonConvert.SerializeObject(theModel);
json = sHelper.createSignEncodingStr(json, SecurityHelper.OrderClientIdKey);//数据参数加密
string retmsg = Utility.PostData(url + "?" + json, Encoding.UTF8);//实现中心点先入库
retmsg = sHelper.decyptData(SecurityHelper.OrderClientIdKey, retmsg);
retMsgNew> result = Newtonsoft.Json.JsonConvert.DeserializeObject>>(retmsg);
return result;
}
public retMsgNew> GetUserByZXDSoftName(string softname, string companyCode, decimal eid, List deptids)
{
if (string.IsNullOrWhiteSpace(companyCode))
{
companyCode = Utility.GetSettingOrNullByKey("DataClientCode");
}
var softuser = softUser_bl.GetUser_userName(softname);
var existsoftName = "";
if (softuser != null)
{
existsoftName = softuser.USERNAME;
}
var url = cacheQ.GetValue_Parameter(Parameter.Core_ZxdService_Api);
url += "ResourceService.svc/SoftUser/GetSoftUserBySoftName";
var theModel = new Soft_User_GetCheckDTO() { companyCode = companyCode, eid = Convert.ToInt32(eid), softusername = softname, existsoftName = existsoftName, deptids = deptids };
string json = Newtonsoft.Json.JsonConvert.SerializeObject(theModel);
json = sHelper.createSignEncodingStr(json, SecurityHelper.OrderClientIdKey);//数据参数加密
string retmsg = Utility.PostData(url + "?" + json, Encoding.UTF8);//实现中心点先入库
retmsg = sHelper.decyptData(SecurityHelper.OrderClientIdKey, retmsg);
retMsgNew> result = Newtonsoft.Json.JsonConvert.DeserializeObject>>(retmsg);
return result;
}
public void BindUser(BindRegUserDto dto)//string username, string unionid, int eid, int ch)
{
try
{
//var resid = string.Empty;
var userList = cacheQ.GetUserList();
var isExe = true;
var pici = new SEQUENCES_BL().Seq_base_get();
using (var db = new crmContext())
{
var user = new SOFT_USER();
if (!string.IsNullOrEmpty(dto.unionId))
user = db.SOFT_USER.FirstOrDefault(p => p.UNIONID == dto.unionId);
if (!string.IsNullOrEmpty(dto.username))
user = db.SOFT_USER.FirstOrDefault(p => p.USERNAME == dto.username);
if (user == null)
{
LogHelper.Info("找不到客户username:" + dto.username + "|||unionid:" + dto.unionId);
return;
}
if (string.IsNullOrEmpty(user.RESID))
{
LogHelper.Info("客户资源resid为空:" + dto.username + " |||unionid:" + dto.unionId);
return;
}
//resid = user.RESID;
//user.EID = eid;
user.UNIONID = dto.unionId;
//LogHelper.Info("regUser.EID:" + user.EID.ToString() + ",regUser.UNIONID:" + user.UNIONID);
if (dto.eid > 0)
{
var eid32 = Convert.ToInt32(dto.eid);
//var userId = userList.FirstOrDefault(p => p.EID == eid32).PKID;
var userEid = _user.getInnerUserByEid(eid32);
var userId = userEid.PKID;
var info = new RES_ALLCOTE_USER()
{
ID = new SEQUENCES_BL().Seq_base_get(),
INNERUSERID = userId,
EID = eid32,
NUM = 1,
CTIME = DateTime.Now,
PICI = pici,
RESID = user.RESID,
TYPE = 1,
DEPTID = userEid.DEPTID
};
if (dto.groupid.HasValue)
{
info.SGID = dto.groupid.Value;
}
var isExists = db.RES_MYALLOCATERES.Any(p => p.RESID == info.RESID);
var isFav = db.CSVR_FAVORITECUSTOMER.Any(p => p.RESID == info.RESID);
var isOrder = db.WX_SZZYORDER.Any(p => p.RESID == info.RESID && p.OTIME != null);
if (isExists)
{
var para = _para.GetModel_Patameter("IgnoreManager");
if (para != null)
{
var myRes = db.RES_MYALLOCATERES.FirstOrDefault(p => p.RESID == info.RESID);
if (myRes != null)
{
var manager = _user.GetModel(myRes.INNERUSERID);
if (!string.IsNullOrEmpty(para.PARAVALUE))
{
var manageList = para.PARAVALUE.Split(',');
foreach (var item in manageList)
{
if (item == manager.EID.ToString())
{
isExists = false;
}
}
}
}
}
}
if (isExists || isFav || isOrder)
{
isExe = false;
}
else
{
db.RES_ALLCOTE_USER.Add(info);
db.SaveChanges();
}
}
}
//资源分配关系
if (dto.eid > 0 && isExe)
{
var eid1000 = userList.FirstOrDefault(p => p.EID == 10000).PKID;
_resMyAllocateRes.ExeSeniorDistributeByResId(eid1000, pici, "扫码直接分配");
}
}
catch (Exception ex)
{
LogHelper.Error("更新软件用户:" + ex.ToString());
}
}
///
/// (当手机号不为空时时进入资源系统,等清洗)从接口抓取到的注册用户,旧系统名称为jmdUser
///
/// 手机号
/// 注册标签
/// 卡号
/// 用户名
/// 注册时间
public bool ImportResApply(string mobile, string tag, string cardNo, string userName, DateTime? regDate, string jsonData = null, string dataType = null, string extXML = null, string kWord = null, decimal? deptid = 0)
{
ValidationErrors errors = new ValidationErrors();
try
{
if (string.IsNullOrEmpty(mobile))
return true;
//WX.CRM.Common.LogHelper.Error("ImportResApply**************************************************");
var model = new WX.CRM.Model.Entity.RES_APPLY
{
PKID = new Base.SEQUENCES_BL().Seq_base_get(WX.CRM.Model.Enum.PKIDType.LargeTable),
RESOURCETAG = tag,
RESID = Common.ResUtil.CreateResId(mobile),
USERNAME = userName,
JSONDATA = jsonData,
RTIME = regDate,
JSONTYPE = 1,
STATUS = 0,
MOBILE = mobile.Trim(),
DATATYPE = dataType,
EXTXML = extXML,
KWORD = kWord,
DEPTID = deptid
};
_apply.Create(ref errors, model);
return true;
}
catch (Exception ex)
{
errors.Add(ex.Message + ex.StackTrace);
//WX.CRM.Common.LogHelper.Error("----------"+ex.Message + ex.StackTrace);
return false;
}
}
public int BuildDeptIdByResId(string resId, decimal? userId = 0, int? ch = 0)
{
try
{
var deptid = 0;
using (WX.CRM.Model.Entity.crmContext db = new WX.CRM.Model.Entity.crmContext())
{
var lineIds = db.BAS_BUSINESSLINES.Select(n => n.BUSINESSID).ToList();
var relation = db.RES_CUSTOMER_RELATION.Where(n => n.RESID == resId && lineIds.Contains(n.DEPTID)).ToList();
//优先根据渠道
if (ch.HasValue && ch > 0)
{
var defaultDept = cacheQ.ConvertChannelName(new List { ch.Value });
if (defaultDept.Count > 0)
{
deptid = Convert.ToInt32(defaultDept.FirstOrDefault().id);
}
}
if (deptid <= 0 && userId > 0)
{
var user = db.BAS_INNERUSER.FirstOrDefault(n => n.PKID == userId);
if (user != null && user.DEPTID.HasValue)
{
deptid = user.DEPTID.Value;
}
}
//在本事业部有数据
if (deptid <= 0 && relation.Count > 0)
{
deptid = relation.FirstOrDefault().DEPTID;
}
if (deptid <= 0)
{
//取辉哥接口
GetResRelationByCms(resId);
relation = db.RES_CUSTOMER_RELATION.Where(n => n.RESID == resId && lineIds.Contains(n.DEPTID)).ToList();
deptid = relation.FirstOrDefault() == null ? 0 : relation.FirstOrDefault().DEPTID;
}
if (deptid > 0)
{
var deptList = cacheQ.GetDeptNameMapList();
var dept = deptList.FirstOrDefault(n => n.id == deptid);
var groupid = 0;
if (dept != null)
{
groupid = Convert.ToInt32(dept.groupId);
RelationDto relationDto = new RelationDto
{
ResId = resId,
DeptId = deptid,
DeptName = dept.title,
GROUPID = groupid
};
_resMyAllocateRes.CreateRelation(relationDto);
}
}
LogHelper.Info($"【{resId}】【{userId}】【{ch}】获取事业部Id{deptid}");
return deptid;
}
}
catch (Exception ex)
{
LogHelper.Error($"获取事业线Id失败{ex.Message}");
return 0;
}
}
///
/// 初始化 后续删除掉
///
public void initDeptIdRelation()
{
using (WX.CRM.Model.Entity.crmContext db = new WX.CRM.Model.Entity.crmContext())
{
var all = db.RES_MYALLOCATERES.Where(n => n.INNERUSERID == 1348683352).ToList();
var userList = db.BAS_INNERUSER.ToList();
foreach (var it in all)
{
var url = "http://centerapi.soft.dn8188.com/Api/AssignUser/GetAssignDetail";
var para = "resid=" + it.RESID;
Dictionary header = new Dictionary();
var res = Utility.GetData(url, para, header, Encoding.UTF8, 3000);
var result = JsonConvert.DeserializeObject>>(res);
if (result.code == 0)
{
it.MEMO = "待删除";
if (result.data.Count == 0)
{
continue;
}
//取辉哥接口
GetResRelationByCms(it.RESID);
LogHelper.Info($"请求cms获取客服归属【{url}】结果{result.ToJson()}");
var eidInfo = result.data.Where(n => n.deptid == it.DEPTID).ToList();
foreach (var item in eidInfo)
{
if (item.eid.HasValue)
{
var user = userList.FirstOrDefault(n => n.EID == item.eid && n.ISDISMISS == 0);
if (user != null)
{
it.INNERUSERID = user.PKID;
it.MEMO = "手动批量分配";
}
}
}
}
}
db.SaveChanges();
}
}
public DateTime GetServiceLastExecTime()
{
DateTime rdate = System.DateTime.Now;
try
{
WX.CRM.Model.Entity.crmContext db = new WX.CRM.Model.Entity.crmContext();
var par = db.BAS_PARAMETER.FirstOrDefault(p => p.PARAKEY.Trim() == "RegUserServiceExecLastTime" && p.GROUPID.Trim() == "SysServiceExecTime");
if (par != null)
rdate = DateTime.Parse(par.PARAVALUE);
else
throw new Exception("RegUserServiceExecLastTime参数错误");
}
catch
{
rdate = System.DateTime.Now;
}
return rdate;
}
public void UpdateExecLastTime(DateTime lastTime)
{
using (WX.CRM.Model.Entity.crmContext db = new WX.CRM.Model.Entity.crmContext())
{
var par = db.BAS_PARAMETER.FirstOrDefault(p => p.PARAKEY.Trim() == "RegUserServiceExecLastTime" && p.GROUPID.Trim() == "SysServiceExecTime");
if (par == null)
{
throw new Exception("RegUserServiceExecLastTime参数错误");
}
par.PARAVALUE = lastTime.ToString();
db.SaveChanges();
}
}
///
/// 通过接口访问分配列表
///
///
///
public bool GetResRelationByCms(string resId)
{
try
{
var url = "http://centerapi.soft.dn8188.com/Api/AssignUser/GetAssignModel";
var para = "resid=" + resId;
Dictionary header = new Dictionary();
var res = Utility.GetData(url, para, header, Encoding.UTF8, 3000);
var result = JsonConvert.DeserializeObject>>(res);
if (result.code == 0)
{
LogHelper.Info($"请求cms获取客服归属【{url}】【{resId}】结果{result.ToJson()}");
var deptList = cacheQ.GetDeptNameMapList();
foreach (var item in result.data)
{
var dept = deptList.FirstOrDefault(n => n.id == item.DeptId);
var groupid = 0;
if (dept != null)
{
groupid = Convert.ToInt32(dept.groupId);
RelationDto relationDto = new RelationDto
{
ResId = resId,
DeptId = Convert.ToInt32(item.DeptId),
DeptName = dept.title,
GROUPID = groupid
};
_resMyAllocateRes.CreateRelation(relationDto);
}
}
}
}
catch (Exception ex)
{
LogHelper.Error($"接口获取客户分配关系失败【{resId}】{ex.Message}");
}
return true;
}
}
public class ComplimentaryProductsJson
{
public int min_ch { get; set; }
public int max_ch { get; set; }
public string deptcode { get; set; }
public IList product { get; set; }
}
public class ComplimentaryProductInfo
{
public string pcode { get; set; }
public string pname { get; set; }
public int days { get; set; }
public int? isremove { get; set; }
}
public class FreeOrderRule
{
public bool IsLimit { get; set; }
public List Products { get; set; }
}
public class FreeProductRule
{
public decimal ProductId { get; set; }
public int Limit { get; set; }
}
public class JsonMessage
{
public int type { get; set; }
public string message { get; set; }
public string value { get; set; }
}
}