ProfitHelper.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Data;
  5. using MySystem.Models.Main;
  6. using Library;
  7. using System.Threading;
  8. using Microsoft.Extensions.Hosting;
  9. using System.Threading.Tasks;
  10. using LitJson;
  11. using MySystem.Models;
  12. namespace MySystem
  13. {
  14. public class ProfitHelper
  15. {
  16. public readonly static ProfitHelper Instance = new ProfitHelper();
  17. private ProfitHelper()
  18. {
  19. }
  20. #region 消费队列(执行消费退款金额的统计)
  21. public void StartListenTrade()
  22. {
  23. Thread th = new Thread(StartListenTradeDo);
  24. th.IsBackground = true;
  25. th.Start();
  26. }
  27. public void StartListenTradeDo()
  28. {
  29. while (true)
  30. {
  31. string orderidstring = RedisDbconn.Instance.RPop<string>("ConsumerOrdersHd:Divi:1:List");
  32. if (!string.IsNullOrEmpty(orderidstring))
  33. {
  34. ReturnStat(orderidstring, 1);
  35. }
  36. else
  37. {
  38. Thread.Sleep(60000);
  39. }
  40. }
  41. }
  42. public void StartListenWxTrade()
  43. {
  44. Thread th = new Thread(StartListenWxTradeDo);
  45. th.IsBackground = true;
  46. th.Start();
  47. }
  48. public void StartListenWxTradeDo()
  49. {
  50. while (true)
  51. {
  52. string orderidstring = RedisDbconn.Instance.RPop<string>("ConsumerOrdersHd:Divi:2:List");
  53. if (!string.IsNullOrEmpty(orderidstring))
  54. {
  55. ReturnStat(orderidstring, 2);
  56. }
  57. else
  58. {
  59. Thread.Sleep(10000);
  60. }
  61. }
  62. }
  63. public void ReturnStat(string orderidstring, int PayMode)
  64. {
  65. function.WriteLog("开始返现:" + orderidstring, "返现逻辑日志");
  66. int OrderId = int.Parse(function.CheckInt(orderidstring));
  67. WebCMSEntities db = new WebCMSEntities();
  68. using (var tran = db.Database.BeginTransaction())
  69. {
  70. try
  71. {
  72. ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == OrderId);
  73. if (order != null)
  74. {
  75. decimal PayMoney = order.PayMoney;
  76. int MerchantId = order.MerchantId;
  77. function.WriteLog("MerchantId:" + MerchantId, "返现逻辑日志");
  78. MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId);
  79. if (merchant != null)
  80. {
  81. int UserId = merchant.UserId;
  82. List<CustomTagSet> customTagSets = db.CustomTagSet.ToList(); //获取公用配置参数集和
  83. //获取参数
  84. CustomTagSet profitPercentSet = customTagSets.FirstOrDefault(m => m.Tags == "CusumerProfitPercent") ?? new CustomTagSet();
  85. decimal profitPercent = decimal.Parse(function.CheckNum(profitPercentSet.Contents)); //基于收款金额的总分润比例;
  86. CustomTagSet cusumerFeePercentSet = customTagSets.FirstOrDefault(m => m.Tags == "CusumerFeePercent") ?? new CustomTagSet();
  87. decimal cusumerFeePercent = decimal.Parse(function.CheckNum(cusumerFeePercentSet.Contents)); //费率;
  88. CustomTagSet minProfitSet = customTagSets.FirstOrDefault(m => m.Tags == "MinProfit") ?? new CustomTagSet();
  89. decimal minProfit = decimal.Parse(function.CheckNum(minProfitSet.Contents)); //最小分润值;
  90. MerchantParamSet set = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(order.SeoDescription);
  91. int DiviPersons = set.DiviPersons; //单笔订单分红人数
  92. decimal DiviPercent = set.DiviPercent; //单人最大分红比例
  93. int ProfitDays = set.ProfitDays; //分红期限(天)
  94. decimal GetPercent = set.GetPercent / 100; //商家实收比例
  95. decimal MinPayMoney = set.MinPayMoney; //订单参与门槛
  96. int IsAll = set.IsAll; //是否收全额
  97. // decimal TotalActual = 0;
  98. if (IsAll == 0 && PayMoney >= MinPayMoney && GetPercent < 1)
  99. {
  100. function.WriteLog("活动开启", "返现逻辑日志");
  101. // PayMoney * (1 - 0.1 - 0.0038 - 0.01);
  102. decimal DiviMoney = PayMoney * (1 - GetPercent - cusumerFeePercent - profitPercent);
  103. if (DiviMoney > 0)
  104. {
  105. function.WriteLog("返现队列开始", "返现逻辑日志");
  106. RedisDbconn.Instance.AddRightList("ConsumerOrdersHd:Divi:" + PayMode + ":" + order.MerchantId, order);
  107. order.ReturnFlag = 1;
  108. db.SaveChanges();
  109. DiviMoney = DiviMoney / DiviPersons;
  110. DiviMoney = PublicFunction.NumberFormat(DiviMoney);
  111. List<int> deletes = new List<int>();
  112. long CurDiviPersons = DiviPersons;
  113. int DiviTimes = 0;
  114. int CheckTime = 0;
  115. long QueueCount = RedisDbconn.Instance.Count("ConsumerOrdersHd:Divi:" + PayMode + ":" + MerchantId);
  116. long CurQueueCount = QueueCount;
  117. if (CurDiviPersons >= CurQueueCount)
  118. {
  119. CurDiviPersons = CurQueueCount;
  120. }
  121. if (DiviPersons < QueueCount)
  122. {
  123. QueueCount = DiviPersons;
  124. }
  125. // 减去自己付的订单
  126. List<int> orderids = new List<int>();
  127. function.WriteLog("人数:" + CurDiviPersons, "返现逻辑日志");
  128. while (CurDiviPersons > 0)
  129. {
  130. ConsumerOrders suborder = RedisDbconn.Instance.RPopLPush<ConsumerOrders>("ConsumerOrdersHd:Divi:" + PayMode + ":" + MerchantId, "ConsumerOrdersHd:Divi:" + PayMode + ":" + MerchantId);
  131. if (suborder != null)
  132. {
  133. decimal TmpCurDivi = suborder.CurDivi;
  134. function.WriteLog("返现对象订单:" + suborder.Id, "返现逻辑日志");
  135. MerchantParamSet subset = Newtonsoft.Json.JsonConvert.DeserializeObject<MerchantParamSet>(suborder.SeoDescription);
  136. int subProfitDays = subset.ProfitDays; //分红期限(天)
  137. bool IsOut = suborder.UpdateDate.Value.AddDays(subProfitDays) < DateTime.Now ? true : false;
  138. if (suborder.CurDivi < suborder.MaxDivi && suborder.MaxDivi - suborder.CurDivi >= 0.01M && !IsOut)
  139. {
  140. function.WriteLog("没出局:" + suborder.CurDivi + "--" + suborder.MaxDivi, "返现逻辑日志");
  141. //如果没过期并且当前退款金额没超过最大退款金额,就执行
  142. decimal GetMoney = suborder.MaxDivi - suborder.CurDivi;
  143. if (GetMoney >= DiviMoney)
  144. {
  145. GetMoney = DiviMoney;
  146. }
  147. function.WriteLog("GetMoney:" + GetMoney, "返现逻辑日志");
  148. if (GetMoney > minProfit)
  149. {
  150. MerchantAddInfo merchantAdd = db.MerchantAddInfo.FirstOrDefault(m => m.Id == suborder.MerchantId) ?? new MerchantAddInfo();
  151. //聚合支付退款
  152. bool BackStatus = false;
  153. //拆单算法
  154. string MerchantList = function.CheckNull(RedisDbconn.Instance.Get<string>("SplitOrderMerchants"));
  155. string SplitOrderStatus = function.CheckNull(RedisDbconn.Instance.Get<string>("SplitOrderStatus"));
  156. if (MerchantList.Contains("," + suborder.MerchantId + ",") || SplitOrderStatus == "1")
  157. {
  158. CheckTime = SplitOrder(suborder.PayMoney, subset.MinPayMoney);
  159. function.WriteLog("CheckTime:" + CheckTime, "返现逻辑日志");
  160. if (CheckTime > 0)
  161. {
  162. if (set.DiviPersons - DiviTimes < CheckTime)
  163. {
  164. CheckTime = set.DiviPersons - DiviTimes;
  165. }
  166. function.WriteLog("CheckTime:" + CheckTime, "返现逻辑日志");
  167. GetMoney = GetMoney * CheckTime;
  168. db.SaveChanges();
  169. function.WriteLog("CurDiviPersons1:" + CurDiviPersons, "返现逻辑日志");
  170. if (RedisDbconn.Instance.Count("ConsumerOrdersHd:Divi:" + PayMode + ":" + MerchantId) >= set.DiviPersons)
  171. {
  172. CurDiviPersons -= CheckTime - 1;
  173. }
  174. function.WriteLog("CurDiviPersons2:" + CurDiviPersons, "返现逻辑日志");
  175. decimal CheckMoney = suborder.MaxDivi - suborder.CurDivi;
  176. if (GetMoney >= CheckMoney)
  177. {
  178. GetMoney = CheckMoney;
  179. }
  180. }
  181. }
  182. suborder.CurDivi += GetMoney;
  183. decimal RefundAmount = GetMoney * 100;
  184. RefundAmount = PublicFunction.NumberFormat(RefundAmount, 0);
  185. if (!orderids.Contains(suborder.Id) && DiviTimes < set.DiviPersons)
  186. {
  187. function.WriteLog("请求退款接口", "返现逻辑日志");
  188. string RefundNo = "HDTK" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
  189. var info = HaoDaHelper.Instance.AggregatedPayRefund(merchantAdd.OutMchtNo, merchantAdd.StoreNo, RefundNo, suborder.OrderNo, RefundAmount.ToString("f0"), merchantAdd.BrandId);
  190. if (info.Contains("\"resultCode\":\"1\"") && info.Contains("\"tradeStatus\":\"2\""))
  191. {
  192. db.ConsumerProfit.Add(new ConsumerProfit()
  193. {
  194. CreateDate = DateTime.Now,
  195. ConsumerId = suborder.ConsumerId,
  196. MerchantId = suborder.MerchantId,
  197. OrderId = suborder.Id,
  198. GetMoney = Math.Round(GetMoney, 2),
  199. QueryCount = PayMode,
  200. Sort = OrderId,
  201. SeoTitle = suborder.OrderNo,
  202. SeoKeyword = suborder.PayMoney.ToString(),
  203. SeoDescription = RefundNo,
  204. });
  205. db.SaveChanges();
  206. BackStatus = true;
  207. }
  208. function.WriteLog("接口返回:" + info, "返现逻辑日志");
  209. orderids.Add(suborder.Id);
  210. DiviTimes += CheckTime;
  211. }
  212. if (BackStatus)
  213. {
  214. merchant.ActCurrentAmount += Math.Round(GetMoney, 2); //活动已返金额
  215. db.SaveChanges();
  216. function.WriteLog(suborder.CurDivi + ":" + suborder.MaxDivi, "返现逻辑日志");
  217. if (suborder.CurDivi < suborder.MaxDivi)
  218. {
  219. function.WriteLog("返现未达最大值继续", "返现逻辑日志");
  220. // RedisDbconn.Instance.AddList("ConsumerOrdersHd:Divi:" + PayMode + ":" + MerchantId, suborder);
  221. RedisDbconn.Instance.SetList("ConsumerOrdersHd:Divi:" + PayMode + ":" + MerchantId, 0, suborder);
  222. RedisDbconn.Instance.AddList("ConsumerOrdersSetDiviHd", "{\"OrderId\":\"" + suborder.Id + "\",\"DiviAmt\":\"" + suborder.CurDivi + "\"}");
  223. }
  224. else
  225. {
  226. suborder.CurDivi = TmpCurDivi;
  227. function.WriteLog("返现达最大值,出局", "返现逻辑日志");
  228. ConsumerOrders editOrder = db.ConsumerOrders.FirstOrDefault(m => m.Id == suborder.Id);
  229. if (editOrder != null)
  230. {
  231. editOrder.ReturnFlag = 0;
  232. db.SaveChanges();
  233. RedisDbconn.Instance.AddList("ConsumerOrdersSetDiviHd", "{\"OrderId\":\"" + suborder.Id + "\",\"DiviAmt\":\"" + suborder.MaxDivi + "\"}");
  234. }
  235. function.WriteLog("删除队列数据:" + Newtonsoft.Json.JsonConvert.SerializeObject(suborder), "返现逻辑日志");
  236. RedisDbconn.Instance.DelFromList("ConsumerOrdersHd:Divi:" + PayMode + ":" + MerchantId, suborder);
  237. }
  238. }
  239. Thread.Sleep(1000);
  240. }
  241. }
  242. else
  243. {
  244. //否者计算人数不计入退款名额
  245. suborder.CurDivi = TmpCurDivi;
  246. function.WriteLog("返现达最大值,出局", "返现逻辑日志");
  247. ConsumerOrders editOrder = db.ConsumerOrders.FirstOrDefault(m => m.Id == suborder.Id);
  248. if (editOrder != null)
  249. {
  250. editOrder.ReturnFlag = 0;
  251. db.SaveChanges();
  252. RedisDbconn.Instance.AddList("ConsumerOrdersSetDiviHd", "{\"OrderId\":\"" + suborder.Id + "\",\"DiviAmt\":\"" + suborder.MaxDivi + "\"}");
  253. }
  254. function.WriteLog("删除队列数据:" + Newtonsoft.Json.JsonConvert.SerializeObject(suborder), "返现逻辑日志");
  255. RedisDbconn.Instance.DelFromList("ConsumerOrdersHd:Divi:" + PayMode + ":" + MerchantId, suborder);
  256. CurDiviPersons += 1;
  257. function.WriteLog("出局:CurDiviPersons:" + CurDiviPersons, "返现逻辑日志");
  258. }
  259. }
  260. CurDiviPersons -= 1;
  261. QueueCount = RedisDbconn.Instance.Count("ConsumerOrdersHd:Divi:" + PayMode + ":" + MerchantId);
  262. function.WriteLog("当前队列数量:" + QueueCount, "返现逻辑日志");
  263. if (QueueCount == 0)
  264. {
  265. CurDiviPersons = 0;
  266. }
  267. }
  268. function.WriteLog("返现队列结束", "返现逻辑日志");
  269. }
  270. }
  271. }
  272. }
  273. else
  274. {
  275. function.WriteLog("没找到订单:" + orderidstring, "返现逻辑日志");
  276. // Thread.Sleep(2000);
  277. // List<ConsumerOrders> list = RedisDbconn.Instance.GetList<ConsumerOrders>("ConsumerOrdersHd:Divi:" + order.PayMode + ":" + order.MerchantId + "", 1, 100000);
  278. // ConsumerOrders check = list.FirstOrDefault(m => m.Id == order.Id);
  279. // bool op = db.ConsumerProfit.Any(m => m.OrderId == order.Id);
  280. // if(check == null && !op)
  281. // {
  282. // RedisDbconn.Instance.AddList("ConsumerOrdersHd:Divi:" + order.PayMode + ":List", order.Id.ToString());
  283. // }
  284. }
  285. tran.Commit();
  286. }
  287. catch (Exception ex)
  288. {
  289. LogHelper.Instance.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "分红返现异常");
  290. tran.Rollback();
  291. RedisDbconn.Instance.AddList("ConsumerProfitCheck", orderidstring);
  292. }
  293. }
  294. db.Dispose();
  295. function.WriteLog("结束返现:" + orderidstring + "\n\n\n", "返现逻辑日志");
  296. }
  297. //拆单算法
  298. private int SplitOrder(decimal OrderAmt, decimal MinMoney)
  299. {
  300. decimal percenter = OrderAmt / MinMoney;
  301. int Times = int.Parse(percenter.ToString().Split('.')[0]);
  302. if (Times < 1) Times = 1;
  303. return Times;
  304. }
  305. #endregion
  306. #region 分润
  307. public void StartListenProfit()
  308. {
  309. Thread th = new Thread(StartListenProfitDo);
  310. th.IsBackground = true;
  311. th.Start();
  312. }
  313. public void StartListenProfitDo()
  314. {
  315. while (true)
  316. {
  317. if (DateTime.Now.Day < 10 && DateTime.Now.Hour > 2 && DateTime.Now.Hour < 23)
  318. {
  319. try
  320. {
  321. DoProfit();
  322. }
  323. catch (Exception ex)
  324. {
  325. LogHelper.Instance.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "来客吧分润异常");
  326. }
  327. Thread.Sleep(600000);
  328. }
  329. else
  330. {
  331. Thread.Sleep(3600000);
  332. }
  333. }
  334. }
  335. //分润算法
  336. public void DoProfit()
  337. {
  338. string TradeMonth = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
  339. string check = function.ReadInstance("/ProfitFlag/" + TradeMonth + ".txt");
  340. if (!string.IsNullOrEmpty(check))
  341. {
  342. return;
  343. }
  344. function.WritePage("/ProfitFlag/", TradeMonth + ".txt", DateTime.Now.ToString());
  345. Models.KxsMain.WebCMSEntities kxsdb = new Models.KxsMain.WebCMSEntities();
  346. WebCMSEntities dbnew = new WebCMSEntities();
  347. DataTable dt = CustomerSqlConn.dtable("select IsAct,UserId,sum(TotalAmount) from UserAmountSummary where TradeMonth='" + TradeMonth + "' and SeoTitle='self' group by IsAct,UserId", AppConfig.Base.SqlConnStr);
  348. foreach (DataRow dr in dt.Rows)
  349. {
  350. int UserId = int.Parse(dr["UserId"].ToString());
  351. bool IsActive = dr["IsAct"].ToString() == "1";
  352. decimal TotalAmount = decimal.Parse(dr[2].ToString());
  353. List<ProfitUsers> users = new List<ProfitUsers>();
  354. int TopUserId = 0; //顶级创客Id
  355. Models.KxsMain.Users us = kxsdb.Users.FirstOrDefault(a => a.Id == UserId);
  356. if (us != null)
  357. {
  358. string uidstring = us.Id.ToString();
  359. if (!string.IsNullOrEmpty(us.ParentNav))
  360. {
  361. uidstring = us.ParentNav.Trim(',').Replace(",,", ",") + "," + uidstring;
  362. string[] parents = us.ParentNav.Trim(',').Replace(",,", ",").Split(',');
  363. if (parents.Length > 1)
  364. {
  365. TopUserId = int.Parse(function.CheckInt(parents[1]));
  366. }
  367. else
  368. {
  369. TopUserId = int.Parse(function.CheckInt(parents[0]));
  370. }
  371. }
  372. string[] uidlist = uidstring.Split(',');
  373. Array.Reverse(uidlist);
  374. foreach (string uidstr in uidlist)
  375. {
  376. int puid = int.Parse(function.CheckInt(uidstr));
  377. Models.KxsMain.Users pus = kxsdb.Users.FirstOrDefault(a => a.Id == puid);
  378. if (pus != null)
  379. {
  380. users.Add(new ProfitUsers()
  381. {
  382. UserId = pus.Id,
  383. MakerCode = pus.MakerCode,
  384. RealName = pus.RealName,
  385. UserNav = pus.ParentNav,
  386. UserLevel = pus.UserLevel,
  387. CreateDate = pus.CreateDate.Value,
  388. });
  389. }
  390. }
  391. }
  392. Models.KxsMain.Users topUser = kxsdb.Users.FirstOrDefault(a => a.Id == TopUserId) ?? new Models.KxsMain.Users();
  393. LogHelper.Instance.WriteLog("---UserId:" + UserId + ";TotalAmount:" + TotalAmount + ";", "来客吧分润日志");
  394. List<ProfitResult> list = new List<ProfitResult>();
  395. list = StartProft(TotalAmount, 1, users, IsActive);
  396. LogHelper.Instance.WriteLog("---list:" + list.Count + ";", "来客吧分润日志");
  397. try
  398. {
  399. foreach (ProfitResult sub in list)
  400. {
  401. int ProfitType = sub.UserId == UserId ? 0 : 1;
  402. ProfitRewardRecord editprofitrecord = dbnew.ProfitRewardRecord.FirstOrDefault(m => m.UserId == sub.UserId && m.BrandId == 1 && m.ProfitType == ProfitType && m.TradeMonth == TradeMonth);
  403. if (editprofitrecord == null)
  404. {
  405. editprofitrecord = dbnew.ProfitRewardRecord.Add(new ProfitRewardRecord()
  406. {
  407. CreateDate = DateTime.Now,
  408. UserId = sub.UserId, //创客
  409. BrandId = 1, //品牌
  410. ProfitType = ProfitType, //创客分润类型
  411. TradeMonth = TradeMonth, //交易月
  412. TopUserId = TopUserId, //顶级创客
  413. CreateMan = sub.MakerCode, //创客编号
  414. UpdateMan = topUser.MakerCode, //顶级编号
  415. SeoTitle = sub.RealName, //创客姓名
  416. SeoKeyword = topUser.RealName, //创客姓名
  417. }).Entity;
  418. dbnew.SaveChanges();
  419. string RecordNo = "KPM";
  420. int RecordId = editprofitrecord.Id;
  421. string RecordIdString = RecordId.ToString();
  422. for (int i = 0; i < 14 - RecordId.ToString().Length; i++)
  423. {
  424. RecordIdString = "0" + RecordIdString;
  425. }
  426. RecordNo += RecordIdString;
  427. editprofitrecord.RecordNo = RecordNo;
  428. dbnew.SaveChanges();
  429. }
  430. if (IsActive)
  431. {
  432. editprofitrecord.CreditTradeAmt += TotalAmount;
  433. editprofitrecord.CreditTradeProfit += sub.Money;
  434. }
  435. else
  436. {
  437. editprofitrecord.TradeAmt += TotalAmount;
  438. editprofitrecord.TradeProfit += sub.Money;
  439. }
  440. dbnew.SaveChanges();
  441. }
  442. dbnew.SaveChanges();
  443. }
  444. catch (Exception ex)
  445. {
  446. LogHelper.Instance.WriteLog(ex.ToString(), "分润异常");
  447. }
  448. }
  449. dbnew.Dispose();
  450. kxsdb.Dispose();
  451. }
  452. #endregion
  453. #region 分润算法
  454. public List<ProfitResult> StartProft(decimal TotalAmount, int LevelKindId, List<ProfitUsers> users, bool IsActive = true)
  455. {
  456. LogHelper.Instance.WriteLog("\n\nTotalAmount:" + TotalAmount + ";", "来客吧分润日志");
  457. string Month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
  458. WebCMSEntities db = new WebCMSEntities();
  459. List<UserLevelSet> levels = db.UserLevelSet.ToList();
  460. List<ProfitResult> result = new List<ProfitResult>();
  461. ProfitObjects obj = db.ProfitObjects.FirstOrDefault();
  462. if (obj.Status == 1) //判断分润是否开启
  463. {
  464. int maxLevel = obj.MaxLevel; //最大等级
  465. int maxFloor = obj.MaxFloor; //最大层级
  466. decimal diffLevelProfit = 0; //等级级差
  467. ProfitObjectLevels maxlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == 9) ?? new ProfitObjectLevels(); //获取最高等级参数
  468. decimal maxPercent = IsActive ? maxlevel.DebitPercents : maxlevel.Percents;
  469. LogHelper.Instance.WriteLog("maxPercent:" + maxPercent + ";", "来客吧分润日志");
  470. decimal maxLevelProfit = TotalAmount * maxPercent;
  471. LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
  472. maxLevelProfit = PublicFunction.NumberFormat(maxLevelProfit);
  473. LogHelper.Instance.WriteLog("maxLevelProfit:" + maxLevelProfit + ";", "来客吧分润日志");
  474. // decimal diffDiviProfit = 0; //分红级差
  475. int curLevel = 0; //当前层级的会员等级
  476. for (int curFloor = 1; curFloor <= users.Count; curFloor++)
  477. {
  478. ProfitUsers user = new ProfitUsers();
  479. if (curFloor <= users.Count)
  480. {
  481. user = users[curFloor - 1];
  482. }
  483. SubUser selfUser = GetUser(user.UserId, Month) ?? new SubUser();
  484. int UserLevel = GetUserLevel(selfUser); //当前会员等级
  485. //判断当前创客是否有直推的激活机具,并且在活动时间内
  486. if (curLevel == maxLevel)
  487. {
  488. break;
  489. }
  490. if (UserLevel <= maxLevel && UserLevel >= curLevel)
  491. {
  492. ProfitObjectLevels objlevel = db.ProfitObjectLevels.FirstOrDefault(m => m.Id == UserLevel); //获取当前等级参数
  493. if (objlevel != null)
  494. {
  495. decimal getLevelProfit = 0; //等级分润
  496. UserProfitSet profitSet = new UserProfitSet();
  497. decimal profitPercent = IsActive ? objlevel.DebitPercents : objlevel.Percents;
  498. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitPercent + ";", "来客吧分润日志");
  499. if (profitPercent > 0)
  500. {
  501. decimal profitTmp = TotalAmount * profitPercent;
  502. getLevelProfit += profitTmp;
  503. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + profitTmp + ";", "来客吧分润日志");
  504. }
  505. decimal money = getLevelProfit;
  506. getLevelProfit -= diffLevelProfit;
  507. if (objlevel.LevelDiff == 1) //判断是否有级差
  508. {
  509. diffLevelProfit = money;
  510. }
  511. if (getLevelProfit >= obj.MinProfitVal)
  512. {
  513. result.Add(new ProfitResult()
  514. {
  515. UserId = user.UserId,
  516. MakerCode = user.MakerCode,
  517. RealName = user.RealName,
  518. UserNav = user.UserNav,
  519. Money = PublicFunction.NumberFormat(getLevelProfit),
  520. ProfitRate = profitSet.ProfitRate,
  521. ProfitPercent = profitSet.ProfitPercent,
  522. AddOrSubRate = profitSet.AddOrSubRate,
  523. ProfitRateBase = profitSet.ProfitRateBase,
  524. });
  525. LogHelper.Instance.WriteLog("money:" + UserLevel + ":" + PublicFunction.NumberFormat(getLevelProfit) + ";", "来客吧分润日志");
  526. }
  527. }
  528. }
  529. if (curLevel < UserLevel)
  530. {
  531. curLevel = UserLevel;
  532. }
  533. }
  534. }
  535. db.Dispose();
  536. return result;
  537. }
  538. public SubUser GetUser(int UserId, string Month)
  539. {
  540. SubUser user = new SubUser();
  541. DataTable dt = GetDataTable("select * from Users" + Month + " where Id=" + UserId);
  542. if (dt.Rows.Count > 0)
  543. {
  544. user.Id = int.Parse(dt.Rows[0]["Id"].ToString());
  545. user.ParentUserId = int.Parse(dt.Rows[0]["ParentUserId"].ToString());
  546. user.ParentNav = dt.Rows[0]["ParentNav"].ToString();
  547. user.UserLevel = int.Parse(dt.Rows[0]["UserLevel"].ToString());
  548. user.PreUserLevel = int.Parse(dt.Rows[0]["PreUserLevel"].ToString());
  549. user.PreLeaderLevel = int.Parse(dt.Rows[0]["PreLeaderLevel"].ToString());
  550. user.PreOpLevel = int.Parse(dt.Rows[0]["PreOpLevel"].ToString());
  551. }
  552. return user;
  553. }
  554. public int GetUserLevel(SubUser user)
  555. {
  556. int level = user.UserLevel;
  557. if (user.PreUserLevel > level) level = user.PreUserLevel;
  558. if (user.PreLeaderLevel > level) level = user.PreLeaderLevel;
  559. if (user.PreOpLevel > level) level = user.PreOpLevel;
  560. return level;
  561. }
  562. public DataTable GetDataTable(string sqlstr)
  563. {
  564. DataTable dt = CustomerSqlConn.dtable(sqlstr, Library.ConfigurationManager.AppSettings["KxsStatSqlConnStr"].ToString());
  565. return dt;
  566. }
  567. #endregion
  568. public void StartSetDivi()
  569. {
  570. Thread th = new Thread(StartSetDiviDo);
  571. th.IsBackground = true;
  572. th.Start();
  573. }
  574. public void StartSetDiviDo()
  575. {
  576. while (true)
  577. {
  578. string content = RedisDbconn.Instance.RPop<string>("ConsumerOrdersSetDiviHd");
  579. if (!string.IsNullOrEmpty(content))
  580. {
  581. SetDivi(content);
  582. }
  583. else
  584. {
  585. Thread.Sleep(10000);
  586. }
  587. }
  588. }
  589. public void SetDivi(string content)
  590. {
  591. try
  592. {
  593. JsonData jsonObj = JsonMapper.ToObject(content);
  594. int orderId = int.Parse(function.CheckInt(jsonObj["OrderId"].ToString()));
  595. decimal diviAmt = decimal.Parse(function.CheckNum(jsonObj["DiviAmt"].ToString()));
  596. WebCMSEntities db = new WebCMSEntities();
  597. ConsumerOrders order = db.ConsumerOrders.FirstOrDefault(m => m.Id == orderId);
  598. if (order != null)
  599. {
  600. order.CurDivi = diviAmt;
  601. db.SaveChanges();
  602. }
  603. db.Dispose();
  604. }
  605. catch (Exception ex)
  606. {
  607. function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "设置订单当前返现金额异常");
  608. }
  609. }
  610. }
  611. }