/// <summary>
        /// 佣金结算
        /// </summary>
        public void SettleCommossionExt()
        {
            try
            {
                ContextSession contextSession = ContextFactory.CurrentThreadContext;
                bool           isContinue     = true;
                int            pageSize       = 100;
                while (true)
                {
                    int shareFacadeErrCnt = 0;
                    var shares            = (from data in ShareDividend.ObjectSet()
                                             join order in CommodityOrder.ObjectSet() on data.CommodityOrderId equals order.Id
                                             join data1 in OrderShareMess.ObjectSet() on data.CommodityOrderId equals data1.OrderId into oshares
                                             from oshare in oshares.DefaultIfEmpty()
                                             join commodity in Commodity.ObjectSet() on order.SrcTagId equals commodity.Id into coms
                                             from com in coms.DefaultIfEmpty()
                                             where data.State == 0 && data.SharerMoney > 0
                                             select new
                    {
                        ShareDividend = data,
                        OrderSrcType = order.SrcType,
                        OrderSrcTagId = order.SrcTagId,
                        OrderCode = order.Code,
                        ShareId = oshare.ShareId,
                        CommodityName = com.Name,
                        OrderSrcAppId = order.SrcAppId,
                        ShareType = data.ShareType,
                        OrderId = order.Id
                    }).Take(pageSize).ToList();
                    if (!shares.Any())
                    {
                        break;
                    }

                    var shareOrderIds = shares.Where(x => x.OrderSrcType == 33).Select(x => x.OrderSrcTagId).ToList();

                    Dictionary <Guid, string> shareOrderCodes = CommodityOrder.ObjectSet()
                                                                .Where(x => shareOrderIds.Contains(x.Id))
                                                                .Select(x => new
                    {
                        Code = x.Code,
                        Id   = x.Id
                    }).ToDictionary(x => x.Id, y => y.Code);

                    for (int i = 0; i < shares.Count; i++)
                    {
                        var    share       = shares[i];
                        Guid   userId      = Guid.Empty;
                        int    roleType    = 1;
                        string description = null;
                        long   money       = share.ShareDividend.SharerMoney;
                        if (share.ShareType == 1) //应用主分成
                        {
                            try
                            {
                                if (share.OrderSrcAppId.HasValue && share.OrderSrcAppId != Guid.Empty)
                                {
                                    var result = APPSV.Instance.GetAppLevelInfo(share.OrderSrcAppId.Value.ToString());
                                    if (result == null)
                                    {
                                        continue;
                                    }
                                    var appScore = result.LevelScore;
                                    if (result.OwnerId == Guid.Empty || appScore < CustomConfig.ShareOwner.AppMinCalcScore)
                                    {
                                        share.ShareDividend.State       = 1;
                                        share.ShareDividend.EntityState = EntityState.Modified;
                                        continue;
                                    }

                                    if (result.OwnerTypeId == (int)App.Deploy.Enum.AppOwnerTypeEnum.Org)
                                    {
                                        roleType = 2;
                                    }
                                    userId = result.OwnerId;

                                    //发送消息
                                    if (result.OwnerTypeId == (int)App.Deploy.Enum.AppOwnerTypeEnum.Org)
                                    {
                                        List <Guid> OrgUserIds = Jinher.AMP.BTP.TPS.EBCSV.Instance.GetUserIdsByOrgIdAndCode(result.OwnerId, "ReceiveRed");

                                        CommodityOrderSV.SendMessageToPayment(OrgUserIds, "affirm", share.ShareDividend.SharerMoney.ToString(CultureInfo.InvariantCulture), null, 0);
                                    }
                                    else if (result.OwnerTypeId == (int)App.Deploy.Enum.AppOwnerTypeEnum.Personal)
                                    {
                                        List <Guid> userIds = new List <Guid> {
                                            result.OwnerId
                                        };
                                        CommodityOrderSV.SendMessageToPayment(userIds, "affirm", share.ShareDividend.SharerMoney.ToString(CultureInfo.InvariantCulture), null, 0);
                                    }
                                }
                                description = string.Format("正品o2o 商品销售分红获得金币{0}个", money);
                            }
                            catch (Exception ex)
                            {
                                LogHelper.Error("佣金结算服务异常:获取应用信息异常。", ex);
                                continue;
                            }
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(share.ShareId) || share.ShareId.ToLower() == "null" || share.ShareId.ToLower() == "undefined")
                            {
                                share.ShareDividend.State       = 1;
                                share.ShareDividend.EntityState = EntityState.Modified;
                                continue;
                            }
                            Jinher.AMP.SNS.Deploy.CustomDTO.ReturnInfoDTO <Guid> shareServiceResult = new SNS.Deploy.CustomDTO.ReturnInfoDTO <Guid>();

                            try
                            {
                                shareServiceResult = Jinher.AMP.BTP.TPS.SNSSV.Instance.GetShareUserId(share.ShareId);
                            }
                            catch (Exception ex)
                            {
                                shareFacadeErrCnt++;
                                LogHelper.Error(string.Format("佣金结算服务异常。调用服务:\"根据分享Id获取分享人Id\" 错误,分享Id={0}", share.ShareId), ex);
                                if (i > 5 && i == shareFacadeErrCnt - 1)
                                {
                                    isContinue = false;
                                    break;
                                }
                                continue;
                            }

                            if (shareServiceResult.Code != "0")
                            {
                                LogHelper.Error(string.Format("佣金结算服务异常。调用服务:\"根据分享Id获取分享人Id\" 不成功,分享Id={0},返回结果={1}", share.ShareId, JsonHelper.JsonSerializer(shareServiceResult)));
                                shareFacadeErrCnt++;
                                //调用服务都为异常,停止本次操作
                                if (i > 5 && i == shareFacadeErrCnt - 1)
                                {
                                    isContinue = false;
                                    break;
                                }
                                continue;
                            }
                            userId = shareServiceResult.Content;
                            switch (share.OrderSrcType)
                            {
                            case 33:
                                //description = string.Format("分享{0}商品获得金币{1}个", share.CommodityName, money);

                                if (share.OrderSrcTagId.HasValue && shareOrderCodes.ContainsKey(share.OrderSrcTagId.Value))
                                {
                                    description = string.Format("分享{0}订单获得金币{1}个", shareOrderCodes[share.OrderSrcTagId.Value], money);
                                }
                                else
                                {
                                    description = string.Format("分享订单获得金币{0}个", money);
                                }
                                break;

                            case 34:
                                //description = string.Format("分享{0}订单获得金币{1}个", share.OrderCode, money);
                                description = string.Format("分享{0}商品获得金币{1}个", share.CommodityName, money);
                                break;
                            }
                        }


                        ShareDividendDetail model = new ShareDividendDetail
                        {
                            Id              = Guid.NewGuid(),
                            UserId          = userId,
                            Money           = money,
                            SettlementDate  = share.ShareDividend.SettlementDate,
                            AppId           = share.ShareDividend.AppId,
                            RoleType        = roleType,
                            ShareDivedendId = share.ShareDividend.Id,
                            Description     = description
                        };
                        model.EntityState = EntityState.Added;
                        contextSession.SaveObject(model);

                        share.ShareDividend.State       = 1;
                        share.ShareDividend.EntityState = EntityState.Modified;
                    }
                    if (!isContinue)
                    {
                        break;
                    }
                    contextSession.SaveChanges();
                    LogHelper.Info(string.Format("佣金结算Job处理了ShareDividend表{0}条记录", shares.Count));
                    if (shares.Count < pageSize)
                    {
                        isContinue = false;
                        break;
                    }
                }

                LogHelper.Info("佣金结算Job处理成功");
            }
            catch (Exception ex)
            {
                LogHelper.Error("佣金结算服务异常。 ", ex);
            }
        }
        /// <summary>
        /// 获取众销明细
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public ShareListResult GetShareListExt(int pageSize, int pageIndex)
        {
            ShareListResult result = new ShareListResult();
            int             start  = (pageIndex - 1) * pageSize;

            result.Count = ShareDividendDetail.ObjectSet().Count();

            if (result.Count > 0)
            {
                result.ShareItems = new List <ShareItemDTO>();

                var orders = (from order in CommodityOrder.ObjectSet()
                              join dividend in ShareDividend.ObjectSet() on order.Id equals dividend.CommodityOrderId
                              join dividendDetail in ShareDividendDetail.ObjectSet() on dividend.Id equals
                              dividendDetail.ShareDivedendId
                              where (order.SrcType == 33 || order.SrcType == 34) && order.State == 3
                              orderby order.SubTime
                              select new ShareItemDTO
                {
                    ShareUserId = dividendDetail.UserId,
                    OrderCode = order.Code,
                    DividendGold = dividendDetail.Money
                }).Skip(start).Take(pageSize).ToList();
                if (orders.Any())
                {
                    var userIds = orders.Select(c => c.ShareUserId).Distinct().ToList();

                    List <UserNameAccountsDTO> userNamelist =
                        CBCSV.Instance.GetUserNameAccountsByIds(userIds) ?? new List <UserNameAccountsDTO>();
                    foreach (var shareItemDto in orders)
                    {
                        string userCode = "--";
                        string userName = "******";

                        var userInfo = userNamelist.FirstOrDefault(c => c.userId == shareItemDto.ShareUserId);
                        if (userInfo != null)
                        {
                            userName = userInfo.userName;
                            if (userInfo.Accounts != null && userInfo.Accounts.Any())
                            {
                                var account = userInfo.Accounts.FirstOrDefault(c => !string.IsNullOrEmpty(c.Account));
                                if (account != null)
                                {
                                    userCode = account.Account;
                                }
                            }
                        }
                        result.ShareItems.Add(new ShareItemDTO
                        {
                            DividendGold  = shareItemDto.DividendGold,
                            OrderCode     = shareItemDto.OrderCode,
                            ShareUserCode = userCode,
                            ShareUserName = userName,
                            ShareDate     = DateTime.Now,
                            ShareUserId   = shareItemDto.ShareUserId
                        });
                    }

                    result.SumUserCount    = ShareDividendDetail.ObjectSet().Select(c => c.UserId).Distinct().Count();
                    result.SumDividendGold = ShareDividendDetail.ObjectSet().Sum(c => c.Money);
                }
            }
            return(result);
        }
        /// <summary>
        /// 发送红包
        /// </summary>
        public void SendRedEnvelopeExt()
        {
            int pageIndex = 0;
            int pageSize  = 500;

            DateTime       today      = DateTime.Now.Date;
            ContextSession session    = ContextFactory.CurrentThreadContext;
            bool           isContinue = true;

            do
            {
                var userDividents = (from s in ShareDividendDetail.ObjectSet()
                                     where s.SettlementDate < today && s.State == 0
                                     group s by s.UserId into g
                                     select g
                                     ).OrderBy(a => a.Key).Take(pageSize).Skip(pageIndex)
                                    .ToDictionary(x => x.Key, y => y.ToList());


                foreach (Guid userId in userDividents.Keys)
                {
                    StringBuilder strDescription = new StringBuilder(50);
                    foreach (ShareDividendDetail userDivident in userDividents[userId])
                    {
                        userDivident.State       = 1;
                        userDivident.EntityState = System.Data.EntityState.Modified;

                        strDescription.Append(userDivident.Description).Append(",");
                    }
                    strDescription.Remove(strDescription.Length - 1, 1);
                    var             goldNum     = userDividents[userId].Sum(x => x.Money);
                    UserRedEnvelope redEnvelope = UserRedEnvelope.CreateUserRedEnvelope();
                    redEnvelope.EntityState = System.Data.EntityState.Added;
                    redEnvelope.AppId       = userDividents[userId][0].AppId;
                    redEnvelope.Content     = CustomConfig.SaleShare.DividentContent;
                    redEnvelope.Description = strDescription.ToString();
                    double dueDateAdd = 24;
                    double.TryParse(CustomConfig.SaleShare.DividentDue, out dueDateAdd);
                    redEnvelope.DueDate   = DateTime.Now.AddHours(dueDateAdd);
                    redEnvelope.GoldCount = goldNum;
                    redEnvelope.UserId    = userId;
                    redEnvelope.RoleType  = userDividents[userId][0].RoleType;

                    ShareRedMessageDTO contentCDTO = new ShareRedMessageDTO();
                    contentCDTO.message  = redEnvelope.Content;
                    contentCDTO.userName = redEnvelope.Content;
                    contentCDTO.msgId    = redEnvelope.Id;
                    contentCDTO.url      = string.Format("{0}ShareRedEnvelope/ShareRedEnvelopesDetail?msgId={1}", CustomConfig.BtpDomain, redEnvelope.Id);

                    double dueMessDateAdd = 48;
                    double.TryParse(CustomConfig.SaleShare.DividentMessageDue, out dueMessDateAdd);

                    if (userDividents[userId][0].RoleType == 2)
                    {
                        try
                        {
                            List <Guid> userIds  = Jinher.AMP.BTP.TPS.EBCSV.Instance.GetUserIdsByOrgIdAndCode(userId, "ReceiveRed");
                            int         msgCount = 0;
                            foreach (Guid id in userIds)
                            {
                                SendMessage(redEnvelope.Id, redEnvelope.AppId, id, DateTime.Now.AddHours(dueMessDateAdd), contentCDTO);
                                //最多选择20个代领者
                                msgCount += 1;
                                if (msgCount > 20)
                                {
                                    break;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error("发送红包Job服务异常:EBC.ISV.Facade.OrganizationQueryFacade。", ex);

                            continue;
                        }
                    }
                    else
                    {
                        SendMessage(redEnvelope.Id, redEnvelope.AppId, redEnvelope.UserId, DateTime.Now.AddHours(dueMessDateAdd), contentCDTO);
                    }

                    session.SaveObject(redEnvelope);
                }

                try
                {
                    session.SaveChanges();
                    if (userDividents.Count < pageSize)
                    {
                        isContinue = false;
                    }
                    LogHelper.Info(string.Format("发送红包Job处理了ShareDividendDetail表{0}条记录", userDividents.Count));
                }
                catch (Exception ex)
                {
                    LogHelper.Error("发送红包Job服务异常。", ex);
                    isContinue = false;
                }
            }while (isContinue);
        }