using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using RFrameGenerate.Common;
using RFrameGenerate.Model;
using RFramework.SQLQuery;
using RFramework.SQLServer;
using RFrameGenerate.Common.ExtensionMethods;
using RFramework.SQLServer.Enums;
using RFrameGenerate.DAL.Enums;
using RFrameGenerate.DAL.Interface;
using System.Drawing;
using RFrameGenerate.Model.PageModel;
using System.Linq.Expressions;
using RFramework.SQLQuery;
using RFramework.SQLQuery.SQLExpands;

namespace RFrameGenerate.BLL
{
    public class DistributionManage
    {
        #region List<T_BAS_DistributionProp> GetDistributionPropList

        /// <summary>
        /// get distributionprop page list
        /// </summary>
        /// <returns></returns>
        public static List<T_BAS_DistributionProp> GetDistributionPropPageList(GridModel gridModel, string name, int isEnable)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                bool enable = (isEnable == 1 ? true : false);
                return query.GetPageList(gridModel, c => c.DistributionName.SqlLike(name) && c.IsEnable == enable, true, b => b.JoinDateTime, OrderMethods.DESC);
            }

        }
        public static List<T_BAS_DistributionProp> GetDistributionPropPageList(GridModel gridModel, Guid? merchantguid, string name, int isEnable)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                bool enable = (isEnable == 1 ? true : false);
                Expression<Func<T_BAS_DistributionProp, bool>> condition = c => c.DistributionName.SqlLike(name) && c.IsEnable == enable;
                if (merchantguid != null && merchantguid != Guid.Empty)
                {
                    condition = condition.AndAlso(a => a.SMerchantGuid == merchantguid);
                }
                else
                {
                    condition = condition.AndAlso(a => a.SMerchantGuid == Common.CurrentManage.MerchantGuid);
                }
                return query.GetPageList(gridModel, condition, true, b => b.JoinDateTime, OrderMethods.DESC, isFilterMerchant: false);
            }

        }

        public static List<T_BAS_DistributionProp> GetDistributionPropPageList(GridModel gridModel, string name)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetPageList(gridModel, c => c.DistributionName.SqlLike(name), true, b => b.JoinDateTime, OrderMethods.DESC);
            }

        }
        /// <summary>
        /// 查询上级分销商
        /// </summary>
        /// <param name="gridModel"></param>
        /// <param name="name"></param>
        /// <param name="filterDistributionGuid">过滤分销商guid</param>
        /// <returns></returns>
        public static List<T_BAS_DistributionProp> GetEnalbeDistributionPropPageList(GridModel gridModel, string name, Guid? filterDistributionGuid = null)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetPageList(gridModel, c => c.DistributionPropGuid != filterDistributionGuid && c.IsEnable == true && c.DistributionName.SqlLike(name), true, b => b.JoinDateTime, OrderMethods.DESC);
            }

        }
        #endregion

        #region List<T_BAS_DistributionProp> GetList
        /// <summary>
        /// get distributionpropDB list
        /// </summary>
        /// <returns></returns>
        public static T_BAS_DistributionProp GetList(Guid distributionPropGuid)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetFirstData(c => c.DistributionPropGuid == distributionPropGuid);
            }
        }
        /// <summary>
        /// get distributionpropDB list by memberguid
        /// </summary>
        /// <returns></returns>
        public static T_BAS_DistributionProp GetList()
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetFirstData(c => c.MemberGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
            }
        }
        #endregion

        ///// <summary>
        ///// T_ST_GetMyTeamByMember get list by merchantGuid
        ///// </summary>
        ///// <returns></returns>
        //public static List<T_ST_GetMyTeamByMember> GetListByDistributionGuid()
        //{
        //    using (var query = Factory.CreateT_ST_GetMyTeamByMember())
        //    {
        //        return query.GetList(c => c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
        //    }
        //}

        public static List<SelectTeam> GetMyTeamList(Guid currentDistributionGuid)
        {
            using (var query = Factory.CreateProcedure())
            {
                return query.GetMyTeamList(currentDistributionGuid);
            }
        }

        /// <summary>
        /// get head dis name
        /// </summary>
        /// <param name="distributionPropGuid"></param>
        /// <returns></returns>
        public static T_BAS_DistributionProp GetHeadName(Guid distributionPropGuid)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetFirstData(c => c.DistributionPropGuid == distributionPropGuid);
                //return dlist == null ? null : dlist.ParentDistributionPropGuid;

            }
        }
        public static List<T_BAS_DistributionProp> GetDistributionAllList()
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetList();
            }
        }

        public static T_BAS_DistributionProp GetHeadByDistributionPropGuid(Guid distributionPropGuid)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetFirstData(c => c.DistributionPropGuid == distributionPropGuid);

            }
        }
        #region Update sub all number
        /// <summary>
        /// this variable is a sign for entry number
        /// </summary>
        public static int Num = 0;
        /// update subnumber
        /// at:on first entry update by distributionGuid
        /// and other by memberguid
        /// </summary>
        /// <param name="subnum"></param>
        /// <param name="distributionGuid"></param>
        /// <returns></returns>
        public static Result UpdataSubNum(int subnum, Guid distributionGuid)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                query.Update(c => new object[]
                    {
                        c.SubMemberNum == subnum,
                    }, a => a.DistributionPropGuid == distributionGuid);
            }
            return new Result(true);
        }

        /// <summary>
        /// 更新上级,上上级团员团队数量
        /// </summary>
        /// <param name="distributionGuid"></param>
        /// <returns></returns>
        public static Result UpdataTeam(Guid distributionGuid, SqlRTransaction tran = null)
        {
            if (distributionGuid == Guid.Empty) return new Result(true);
            bool isdispose = false;
            if (tran == null)
            {
                isdispose = true;
                tran = new SqlRTransaction();
            }
            var query = Factory.CreateT_BAS_DistributionProp(tran);

            var current = query.GetFirstData(a => a.DistributionPropGuid == distributionGuid);
            //当前分销不存在
            if (current == null)
                return new Result(true);

            //没有父级
            if (current.ParentDistributionPropGuid == null || current.ParentDistributionPropGuid == Guid.Empty)
                return new Result(true);

            try
            {
                tran.BeginTransaction();
                UpdataTeam(current.ParentDistributionPropGuid, query);
                tran.Commit();
                return new Result(true);
            }
            catch (Exception ex)
            {
                tran.Rollback();
                return new Result(false, ex.Message);
            }
            finally
            {
                if (isdispose == true)
                    tran.Dispose();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentDistributionGuid"></param>
        /// <param name="query"></param>
        /// <param name="level">递归级别,-1,无限递归</param>
        static void UpdataTeam(Guid? parentDistributionGuid, IQuery<T_BAS_DistributionProp> query, int level = 2)
        {
            if (level != -1)
            {
                if (level-- == 0)
                    return;//遍历级别
            }

            if (parentDistributionGuid == null || parentDistributionGuid == Guid.Empty)
                return;//没有上级

            var superior = query.GetFirstData(a => a.DistributionPropGuid == parentDistributionGuid);

            if (superior == null)
                return;//没找到上级

            int subnum = (superior.SubMemberNum ?? 0) + 1;
            //更新团队
            query.Update(a => new object[] { a.SubMemberNum == subnum }, b => b.DistributionPropGuid == parentDistributionGuid);

            UpdataTeam(superior.ParentDistributionPropGuid, query, level);
        }


        public static Result UpdateSuperior(Guid id, Guid prentid, Guid? memguid)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    var queryMem = Factory.CreateT_BAS_Member(tran);
                    if (prentid != Guid.Empty)
                        queryMem.Update(a => new object[] { a.DID == prentid }, b => b.MemberGuid == memguid);
                    else
                        queryMem.Update(a => new object[] { a.DID == null }, b => b.MemberGuid == memguid);


                    var query = Factory.CreateT_BAS_DistributionProp(tran);
                    tran.BeginTransaction();

                    //更新原来上级的团队数量
                    var dist = query.GetFirstData(a => a.DistributionPropGuid == id);

                    if (dist.ParentDistributionPropGuid == prentid)
                        return new Result(false, dist.SuperiorName + "已经是你的上级");

                    if (dist.ParentDistributionPropGuid != null && dist.ParentDistributionPropGuid != Guid.Empty)
                    {
                        //原来上级要减去团队数量=当前选择[1]+当前选择的一级团队数量
                        var dist1 = query.GetFirstData(a => a.DistributionPropGuid == dist.ParentDistributionPropGuid);
                        if (dist1 != null)
                        {
                            int count1 = dist1.SubMemberNum.Value - query.GetCount(a => a.ParentDistributionPropGuid == dist.DistributionPropGuid) - 1;
                            query.Update(a => new object[] { a.SubMemberNum == count1 }, b => b.DistributionPropGuid == dist1.DistributionPropGuid);

                            //原来上上级要减去团队数量=当前选择[1]
                            if (dist1.ParentDistributionPropGuid != null && dist1.ParentDistributionPropGuid != Guid.Empty)
                            {
                                var dist11 = query.GetFirstData(a => a.DistributionPropGuid == dist1.ParentDistributionPropGuid);
                                if (dist11 != null)
                                {
                                    int count11 = dist11.SubMemberNum.Value - 1;
                                    query.Update(a => new object[] { a.SubMemberNum == count11 }, b => b.DistributionPropGuid == dist11.DistributionPropGuid);
                                }
                            }
                        }


                    }

                    if (prentid != Guid.Empty)
                    {
                        var newdist1 = query.GetFirstData(a => a.DistributionPropGuid == prentid);
                        if (newdist1 != null)
                        {
                            //更新新的上级团队数量   //原来上级要加上团队数量=当前选择[1]+当前选择的一级团队数量
                            int newcount1 = newdist1.SubMemberNum.Value + query.GetCount(a => a.ParentDistributionPropGuid == dist.DistributionPropGuid) + 1;
                            query.Update(a => new object[] { a.SubMemberNum == newcount1 }, b => b.DistributionPropGuid == newdist1.DistributionPropGuid);
                            //修改自己的上级
                            query.Update(a => new object[] { a.ParentDistributionPropGuid == prentid, a.SuperiorName == newdist1.DistributionName }, b => b.DistributionPropGuid == id);
                            //更新新的上上级团队数量  //原来上上级要减加上团队数量=当前选择[1]
                            if (newdist1.ParentDistributionPropGuid != null && newdist1.ParentDistributionPropGuid != Guid.Empty)
                            {
                                var newdist11 = query.GetFirstData(a => a.DistributionPropGuid == newdist1.ParentDistributionPropGuid);
                                if (newdist11 != null)
                                {
                                    int newcount11 = newdist11.SubMemberNum.Value + 1;
                                    query.Update(a => new object[] { a.SubMemberNum == newcount11 }, b => b.DistributionPropGuid == newdist11.DistributionPropGuid);
                                }
                            }
                        }
                    }
                    else
                    {
                        query.Update(a => new object[] { a.ParentDistributionPropGuid == null, a.SuperiorName == "总部" }, b => b.DistributionPropGuid == id);
                    }
                    tran.Commit();
                }

                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }


        /// <summary>
        /// check has parentGuid
        /// </summary>
        /// <param name="distributionGuid"></param>
        /// <returns></returns>
        public static int HasParentGuid(Guid distributionGuid)
        {
            var parentGuid = GetParentGuid(distributionGuid);
            if (parentGuid != Guid.Empty)
            {
                return DistributionManage.GetSubNum(parentGuid);
            }
            return -1;
        }
        /// <summary>
        /// get subnumber 
        /// at:on first entry distributionPropGuid assignment to fatherguid
        /// and comparison with him
        /// </summary>
        /// <param name="distributionPropGuid"></param>
        /// <returns></returns>
        public static int GetSubNum(Guid distributionPropGuid)
        {

            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                var subNumData = query.GetFirstData(c => c.DistributionPropGuid == distributionPropGuid);
                if (subNumData == null)
                    return -1;
                return subNumData.SubMemberNum ?? -1;
            }
        }
        /// <summary>
        /// get parentGuid by distributionpropguid
        /// at:return distrbutionPropGuid by first entry
        /// and other return parentmemberguid
        /// </summary>
        /// <param name="distributionPropGuid"></param>
        /// <returns></returns>
        public static Guid GetParentGuid(Guid distributionPropGuid)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                var parentMember = query.GetFirstData(c => c.DistributionPropGuid == distributionPropGuid);
                if (parentMember == null) return Guid.Empty;
                return parentMember.ParentDistributionPropGuid ?? Guid.Empty;

            }
        }

        #endregion


        #region Update sub all number count
        /// <summary>
        /// this variable is a sign for entry number count
        /// </summary>
        public static int Len = 0;

        public static List<T_BAS_DistributionProp> GetListByParentDistributionPropGuid(Guid distributionGuid)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                var list = query.GetList(c => c.ParentDistributionPropGuid == distributionGuid);
                return list;

            }

        }


        #endregion
        /// <summary>
        /// get name
        /// </summary>
        /// <returns></returns>
        public static string GetName(Guid guid, Guid memberGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                //string guid;
                //try
                //{
                //    guid = CookieManage.GetCookie(SessionKeys.ShareDistribution);
                //    if (guid==null)
                //    {
                //        return "总部";
                //    }
                //}
                //catch (Exception)
                //{
                //    return "总部";
                //    throw;
                //}
                //return query.GetFirstData(c => c.MemberGuid == Guid.Parse(guid)).DistributionName;

                //var model = query.GetFirstData(c => c.MemberGuid == memberGuid);
                var query = Factory.CreateT_BAS_DistributionProp(tran);
                var query_member = Factory.CreateT_BAS_Member(tran);
                var model_member = query_member.GetDataByGuid(memberGuid);
                return model_member == null ? "" : model_member.MemberName;
            }
        }
        /// <summary>
        /// get name
        /// </summary>
        /// <returns></returns>
        public static string GetName()
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_DistributionProp(tran);

                var mydist = query.GetFirstData(a => a.MemberGuid == CurrentUser.GetCurrUserGuid());
                if (mydist == null)
                {
                    var queryMember = Factory.CreateT_BAS_Member(tran);
                    return queryMember.GetFirstData(a => a.MemberGuid == CurrentUser.GetCurrUserGuid()).MemberName;
                }
                else
                {
                    return mydist.DistributionName;
                }
            }
        }

        public static string GetShareName()
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_DistributionProp(tran);
                Guid? did = MemberManage.GetParentDID(OpenIDManage.GetOpenID());
                if (did == null)
                {
                    return "总部";
                }
                var dist = query.GetFirstData(c => c.DistributionPropGuid == did);
                if (dist == null)
                {
                    CookieManage.SetCookie(SessionKeys.ShareDistribution, string.Empty, 1);
                    return "总部";
                }
                return dist.DistributionName;
            }
        }
        public static string GetShareTitle()
        {
            using (var tran = new SqlRTransaction())
            {
                var DistributionStoreInfo = ParameterManage.GetParam(ParameterName.DistributionMemeber.DistributionStoreInfo);
                if (DistributionStoreInfo != null)
                {
                    if (DistributionStoreInfo.ParameterValue.ToLower() == RFrameGenerate.BLL.DictionaryConst.DistributionStoreInfo.Disable.ToString())
                    {
                        //分销商自定义店铺名称和Logo:
                        using (var queryMerch = Factory.CreateT_BAS_Merchants(tran))
                        {
                            var merch = queryMerch.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                            return merch.StoreTitle;
                        }
                    }
                }


                var query = Factory.CreateT_BAS_DistributionProp(tran);
                Guid? did = MemberManage.GetParentDID(OpenIDManage.GetOpenID());
                if (did == null)
                {//总部
                    var queryMerch = Factory.CreateT_BAS_Merchants(tran);
                    var merch = queryMerch.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                    return merch.StoreTitle;
                }
                //分销商
                var dist = query.GetFirstData(c => c.DistributionPropGuid == did);
                if (dist == null)
                {//总部
                    CookieManage.SetCookie(SessionKeys.ShareDistribution, string.Empty, 1);
                    var queryMerch = Factory.CreateT_BAS_Merchants(tran);
                    var merch = queryMerch.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                    return merch.StoreTitle;
                }
                else if (string.IsNullOrEmpty(dist.StoreTitle) == true)
                {//总部
                    //var queryMerch = Factory.CreateT_BAS_Merchants(tran);
                    //var merch = queryMerch.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                    //return merch.StoreTitle;
                    return dist.DistributionName + "的小店";
                }
                else
                {
                    return dist.StoreTitle;
                }
            }
        }


        public static string GetAttentionShareTitle(string openid)
        {
            using (var tran = new SqlRTransaction())
            {
                var member = Factory.CreateT_BAS_Member(tran).GetFirstData(a => a.MemberOpenID == openid, false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                CurrentUser.SetMerchantGuid(member.MerchantGuid.Value);
                CurrentUser.SetSMerchantGuid(member.MerchantGuid.Value);
                var DistributionStoreInfo = ParameterManage.GetParam(ParameterName.DistributionMemeber.DistributionStoreInfo);
                if (DistributionStoreInfo != null)
                {
                    if (DistributionStoreInfo.ParameterValue.ToLower() == RFrameGenerate.BLL.DictionaryConst.DistributionStoreInfo.Disable.ToString())
                    {
                        //分销商自定义店铺名称和Logo:
                        using (var queryMerch = Factory.CreateT_BAS_Merchants(tran))
                        {
                            var merch = queryMerch.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                            return merch.StoreTitle;
                        }
                    }
                }


                var query = Factory.CreateT_BAS_DistributionProp(tran);
                Guid? did = MemberManage.GetParentDID(openid);
                if (did == null)
                {//总部
                    var queryMerch = Factory.CreateT_BAS_Merchants(tran);
                    var merch = queryMerch.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                    return merch.StoreTitle;
                }
                //分销商
                var dist = query.GetFirstData(c => c.DistributionPropGuid == did);
                if (dist == null)
                {//总部
                    CookieManage.SetCookie(SessionKeys.ShareDistribution, string.Empty, 1);
                    var queryMerch = Factory.CreateT_BAS_Merchants(tran);
                    var merch = queryMerch.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                    return merch.StoreTitle;
                }
                else if (string.IsNullOrEmpty(dist.StoreTitle) == true)
                {//总部

                    return dist.DistributionName + "的小店";
                }
                else
                {
                    return dist.StoreTitle;
                }
            }
        }

        public static string GetTime()
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                string guid;
                try
                {
                    guid = CookieManage.GetCookie(SessionKeys.ShareDistribution);
                }
                catch (Exception)
                {
                    throw;
                }
                return query.GetFirstData(c => c.DistributionPropGuid == Guid.Parse(guid)).JoinDateTime.ToString();

            }
        }

        /// <summary>
        /// show qrcode
        /// </summary>
        /// <returns></returns>
        public static string ShowQRCode(string openId)
        {
            using (var tran = new SqlRTransaction())
            {
                //var query = Factory.CreateT_BAS_DistributionProp(tran);
                var did = CookieManage.GetCookie(SessionKeys.ShareDistribution);
                if (string.IsNullOrEmpty(did))
                {
                    var queryme = Factory.CreateT_WX_WeChat(tran);
                    var wechat = queryme.GetFirstData(a => a.appid == CurrentManage.AppId);
                    return wechat.qrcode_url;
                }
                //return query.GetFirstData(c => c.DistributionPropGuid == Guid.Parse(guid)).RQCode;

                string path = AppDomain.CurrentDomain.BaseDirectory + "upload\\tempqrcode\\Distribution\\" + CurrentManage.MerchantUserID;
                var str = CurrentManage.CurrentDomainWx + "WxShop/Index?did=" + did + "&inviter=" + openId;

                string pathfile = System.IO.Path.Combine(path, did + ".jpg");
                if (System.IO.File.Exists(pathfile) != true)
                    DistributionManage.GetQRcode(str, "", path, Guid.Parse(did), false);

                return "/upload/tempqrcode/Distribution/" + CurrentManage.MerchantUserID + "/" + did + ".jpg";

            }
        }

        /// <summary>
        /// Update function by memberguid and applyAmount(update balance)
        /// </summary>
        /// <param name="distributionPropGuid"></param>
        /// <param name="amountFrozen"></param>
        /// <param name="withdrawalAmount"></param>
        /// <returns></returns>
        public static Result UpdateAmount(Guid distributionPropGuid, decimal amountFrozen, decimal withdrawalAmount)
        {

            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                query.Update(a => new object[]
                {
                    a.AmountFrozen == amountFrozen,
                    a.WithdrawalAmount==withdrawalAmount
                }, b => b.DistributionPropGuid == distributionPropGuid);

                return new Result(true);
            }
        }

        public static Result DelMember(Guid didGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_DistributionProp(tran);
                var queryRecord = Factory.CreateT_BAS_ApplyDistributionRecords(tran);
                var queryMember = Factory.CreateT_BAS_Member(tran);
                var queryBind = SQLModelFactory.CreateSqlModel<T_BAS_MemberBindMerchant>(tran);
                var queryMer = SQLModelFactory.CreateSqlModel<T_BAS_Merchants, T_BAS_Member>(tran);

                var prop = query.GetFirstData(a => a.DistributionPropGuid == didGuid);
                if (prop != null)
                {
                    tran.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                    //分销商删除
                    query.Delete(a => a.DistributionPropGuid == prop.DistributionPropGuid);
                    //会员关系,状态清空
                    queryMember.Update(a => new object[] { a.DID == null, a.IsDistributor == false, }, b => b.MemberGuid == prop.MemberGuid);
                    //申请记录清空
                    queryRecord.Delete(a => a.MemberGuid == prop.MemberGuid);
                    //清空其它会员的锁定关系,变为总部
                    queryMember.Update(a => new object[] { a.DID == null }, b => b.DID == prop.DistributionPropGuid);
                    //下级分销商上级清空
                    query.Update(a => new object[] { a.ParentDistributionPropGuid == null, a.SuperiorName == "总部" }, b => b.ParentDistributionPropGuid == prop.DistributionPropGuid);

                    //删除关系
                    var mer = queryMer.SqlSelect((a, b) => new { a.UserID, b.MemberOpenID }).SqlJionInner((a, b) => b).SqlOn((a, b) => a.MerchantGuid == b.MerchantGuid).SqlWhere((a, b) => b.MemberGuid == prop.MemberGuid).FirstOrDefault();
                    if (mer != null && mer.UserID != null)
                    {
                        queryBind.SqlDelete(a => a.UserID == mer.UserID && a.NewOpenID == mer.MemberOpenID);
                    }
                    tran.Commit();
                }
                else
                {
                    return new Result(false, "分销商不存在");
                }
            }
            return new Result(true);
        }

        #region Result ChangeStateByStateCode
        /// <summary>
        /// update state 
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="stateCode"></param>
        /// <returns></returns>
        public static Result ChangeStateByStateCode(Guid guid, bool stateCode)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                query.Update(c => new object[]
                {
                    c.IsEnable == stateCode,
                }, a => a.DistributionPropGuid == guid);
            }
            return new Result(true);
        }
        #endregion

        #region Result GetQRcode
        /// <summary>
        /// get qrcode
        /// </summary>
        /// <param name="value"></param>
        /// <param name="text"></param>
        /// <param name="path"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static Result GetQRcode(string value, string text, string path, Guid guid, bool isAddDateTimeRoot = true)
        {
            CreateFloderHelper createFloderHelper = new CreateFloderHelper();
            string newpath = "";
            if (isAddDateTimeRoot == true)
            {
                newpath = createFloderHelper.CreateFloderByDateTime(path);
            }
            else
            {
                newpath = path;
            }
            string filename = newpath + "\\" + guid + ".jpg";
            var result = QrCodeHelper.GenerationQrCode(value, text, filename);
            if (result)
            {
                var str = filename.Split('\\');
                var sqlPath = "/" + str[str.Length - 4] + "/" + str[str.Length - 3] + "/" + str[str.Length - 2] + "/" + str[str.Length - 1];
                return UpdateQRcodePath(guid, sqlPath);
            }
            else
            {
                return new Result(false);
            }

        }
        #endregion

        #region Result UpdateQRcodePath
        /// <summary>
        /// update qrchdePath
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="qrcodePath"></param>
        /// <returns></returns>
        public static Result UpdateQRcodePath(Guid guid, string qrcodePath)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {

                query.Update(c => new object[]
                {
                    c.RQCode==qrcodePath
                }, a => a.DistributionPropGuid == guid);
            }
            return new Result(true, qrcodePath);
        }
        #endregion

        #region Result AddApplyDistributionData

        /// <summary>
        /// add applylist to distributionprop
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="memberGuid"></param>
        /// <returns></returns>
        public static Guid AddApplyDistributionData(T_BAS_DistributionProp entity, Guid memberGuid, string applydatetime)
        {
            var disGuid = Guid.NewGuid();
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_DistributionProp(tran);
                entity.DistributionPropGuid = disGuid;
                entity.MemberGuid = memberGuid;
                entity.JoinDateTime = DateTime.Now;
                entity.DistributionAmount = 0;
                entity.WithdrawalAmount = 0;
                entity.DistributionCommissions = 0;
                query.Add(entity);

                #region 模板消息
                try
                {
                    if (entity.ParentDistributionPropGuid != null && entity.ParentDistributionPropGuid != Guid.Empty)
                    {
                        var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                        var queryMem = Factory.CreateT_BAS_Member(tran);
                        var member = queryMem.GetFirstData(a => a.MemberGuid == memberGuid);
                        var merchGuid = HeadPay.GetPayMerchantGuid(CurrentManage.MerchantUserID);
                        var template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.分销商申请成功提醒, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                        if (template != null)
                        {
                            Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                            send.first = new Wechat.Model.TempateKey("first", "恭喜您已经成为分销商");
                            send.keys = new List<Wechat.Model.TempateKey>();
                            send.keys.Add(new Wechat.Model.TempateKey("keyword1", entity.DistributionName));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword2", entity.DistributionTelphone));
                            send.keys.Add(new Wechat.Model.TempateKey("keyword3", applydatetime));
                            send.remark = new Wechat.Model.TempateKey("remark", "如有疑问，请在微信中留言，我们将第一时间为您服务。");
                            weixinopen.WeiXinOpenRequest.SendMessageTemplate(member.MemberOpenID, template.TemplateID, CurrentManage.CurrentDomainWx + "DistributionCenter/Index", send, CurrentManage.AppId);
                        }
                        template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.新代理加入通知, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                        if (template != null)
                        {
                            //上级
                            var supDistribution = query.GetFirstData(a => a.DistributionPropGuid == entity.ParentDistributionPropGuid.Value);
                            if (supDistribution != null)
                            {
                                var supMember = MemberManage.GetMemberByGuid(supDistribution.MemberGuid.Value);
                                if (supMember != null)
                                {
                                    Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                                    send.first = new Wechat.Model.TempateKey("first", "有一位新成员加入您的团队，赶紧去看看吧。");
                                    send.keys = new List<Wechat.Model.TempateKey>();
                                    send.keys.Add(new Wechat.Model.TempateKey("keyword1", entity.DistributionName));
                                    send.keys.Add(new Wechat.Model.TempateKey("keyword2", member.WeChatName));
                                    send.keys.Add(new Wechat.Model.TempateKey("keyword3", entity.DistributionTelphone));
                                    send.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。");

                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(supMember.MemberOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", CurrentManage.MerchantUserID)) + "DistributionCenter/Index", send, Common.CurrentManage.AppId);
                                }

                                //上上级
                                if (supDistribution.ParentDistributionPropGuid != null)
                                {
                                    var topDistribution = query.GetFirstData(a => a.DistributionPropGuid == supDistribution.ParentDistributionPropGuid.Value);
                                    if (topDistribution != null)
                                    {
                                        var topMember = MemberManage.GetMemberByGuid(topDistribution.MemberGuid.Value);
                                        if (topMember != null)
                                        {
                                            Wechat.Model.SendTempateKey sendTop = new Wechat.Model.SendTempateKey();
                                            sendTop.first = new Wechat.Model.TempateKey("first", "有一位新成员加入您的团队，赶紧去看看吧。");
                                            sendTop.keys = new List<Wechat.Model.TempateKey>();
                                            sendTop.keys.Add(new Wechat.Model.TempateKey("keyword1", entity.DistributionName));
                                            sendTop.keys.Add(new Wechat.Model.TempateKey("keyword2", member.WeChatName));
                                            sendTop.keys.Add(new Wechat.Model.TempateKey("keyword3", entity.DistributionTelphone));
                                            sendTop.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                            weixinopen.WeiXinOpenRequest.SendMessageTemplate(topMember.MemberOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", Common.CurrentManage.MerchantUserID)) + "DistributionCenter/Index", sendTop, Common.CurrentManage.AppId);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Wechat.LogManage.Log("成功分销商发送模板出错" + ex.Message);
                }

                #endregion

            }

            return disGuid;
        }
        #endregion

        public static Result AddReseller(T_BAS_DistributionProp entity)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                query.Add(entity);
            }
            return new Result(true);
        }

        #region T_BAS_Distribute GetEntityByOrder
        /// <summary>
        /// get eneity by order guid
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static T_BAS_Distribute GetEntityByOrder(Guid guid)
        {
            using (var query = Factory.CreateT_BAS_Distribute())
            {
                return query.GetFirstData(a => a.OrderGuid == guid);
            }
        }


        public static T_BAS_DistributionProp GetPropByOrder(Guid guid)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetFirstData(a => a.DistributionPropGuid == guid, isFilterMerchant: false);
            }
        }
        #endregion

        #region 分销订单列表(分页)
        public static List<T_ST_DistributeOrder> GetPageList(GridModel gridModel, string orderState, string disName, string orderNo)
        {
            var tran = new SqlRTransaction();
            try
            {
                //原来逻辑
                List<T_ST_DistributeOrder> list = new List<T_ST_DistributeOrder>();
                //using (var query = Factory.CreateT_ST_DistributeOrder())
                //{
                //    list = query.GetPageList(gridModel, null, true, a => a.CreateDate, OrderMethods.DESC);
                //}

                //处理运费返佣 zhou 2016/4/6               
                var query = Factory.CreateProcedure(tran);
                return query.GetDistribution_Order_List(gridModel.page, gridModel.rows, out gridModel.pageCount, out gridModel.recordCount, CurrentManage.MerchantGuid, orderState, disName, orderNo);

            }
            finally
            {
                tran.Dispose();
            }
        }
        #endregion

        #region 结算分销佣金（新）
        public static Result GetTotalAmount()
        {
            List<MessageBox> messageBox = new List<MessageBox>();
            string msg = "";
            //分销佣金
            using (var tran = new SqlRTransaction())
            {
                var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                var querywechat = Factory.CreateT_WX_WeChat(tran);
                var merchGuid = HeadPay.GetPayMerchantGuid(CurrentManage.MerchantUserID);
                var template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.佣金提醒, isFilterMerchant: false);
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_parameter = Factory.CreateT_SYS_Parameter(tran);
                var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                var query_distributionProp = Factory.CreateT_BAS_DistributionProp(tran);
                var query_distributionCommissions = Factory.CreateT_BAS_DistributionCommissions(tran);
                var query_distribute = Factory.CreateT_BAS_Distribute(tran);
                var query_merchant = Factory.CreateT_BAS_Merchants(tran);
                var query_member = Factory.CreateT_BAS_Member(tran);
                var query_withdrawsCommission = Factory.CreateT_BAS_WithdrawsCommission(tran);
                var query_product = Factory.CreateProcedure(tran);
                //var query_distributeOrder = Factory.CreateT_ST_DistributeOrder(tran);
                var query_InTrade = Factory.CreateT_INT_IntegralTrading(tran);
                var merchant = query_merchant.GetFirstData(a => a.MerchantGuid == CurrentManage.MerchantGuid);
                T_BAS_DistributionProp model_prop_first = null;
                T_BAS_DistributionProp model_prop_second = null;
                T_BAS_DistributionProp model_prop_third = null;
                try
                {
                    tran.BeginTransaction();
                    List<T_BAS_Orders> list_order = query_order.GetList(a => a.IsDistribute == true && a.OrderState == DictionaryConst.OrderState.Completed && a.MerchantGuid == CurrentManage.MerchantGuid, false, null);
                    if (list_order.Count == 0)
                    {
                        // messageBox.Add(new MessageBox(false, "没有满足条件的分销订单需结算"));
                        return new Result(false, "没有满足条件的分销订单需结算");
                    }
                    #region 1、验证参数
                    T_SYS_Parameter model_parameter = query_parameter.GetFirstData(a => a.ParameterName == ParameterName.CommissionMember.CommissionSettlementTime && a.MerchantGuid == CurrentManage.MerchantGuid);
                    if (model_parameter == null)
                    {
                        //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "未设置佣金结算时间"));
                        return new Result(false, "未设置佣金结算时间");
                    }
                    //T_SYS_Parameter model_parameter_firstCommission = query_parameter.GetFirstData(a => a.ParameterName == ParameterName.CommissionMember.FirstCommission && a.MerchantGuid == CurrentManage.MerchantGuid);
                    //if (model_parameter_firstCommission == null)
                    //{
                    //    //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "未设置一级佣金结算比例"));
                    //    return new Result(false, "未设置一级佣金结算比例");
                    //}
                    //T_SYS_Parameter model_parameter_secondCommission = query_parameter.GetFirstData(a => a.ParameterName == ParameterName.CommissionMember.SecondCommission && a.MerchantGuid == CurrentManage.MerchantGuid);
                    //if (model_parameter_secondCommission == null)
                    //{
                    //    //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "未设置二级佣金结算比例"));
                    //    return new Result(false, "未设置二级佣金结算比例");
                    //}
                    //T_SYS_Parameter model_parameter_thirdCommission = query_parameter.GetFirstData(a => a.ParameterName == ParameterName.CommissionMember.ThirdCommission && a.MerchantGuid == CurrentManage.MerchantGuid);
                    //if (model_parameter_thirdCommission == null)
                    //{
                    //    //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "未设置三级佣金结算比例"));
                    //    return new Result(false, "未设置三级佣金结算比例");

                    //}
                    #endregion
                    try
                    {
                        //2.	结算逻辑：
                        //a)	符合条件的分销订单：订单完成时间+参数030204>当前时间 
                        foreach (T_BAS_Orders item in list_order)
                        {
                            if (item.CompletedTime == null)
                            {
                                continue;
                            }
                            if ((DateTimeEx.DateDiff(item.CompletedTime.Value) < int.Parse(model_parameter.ParameterValue) && int.Parse(model_parameter.ParameterValue) != 0))
                            {
                                messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "该订单不满足佣金结算时间限制"));
                                continue;
                            }

                            #region 2、验证分销订单是否符合结算条件
                            var model_distribute = query_distribute.GetFirstData(a => a.OrderGuid == item.OrderGuid && a.MerchantGuid == item.MerchantGuid);
                            //是否有分销订单
                            if (model_distribute == null)
                            {
                                messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "找不到与该订单相关联的分销订单"));
                                continue;
                            }
                            if (item.CompletedTime == null)
                            {
                                messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "该订单尚未完成"));
                                continue;
                            }

                            //分销订单是否已结算
                            if (model_distribute.IsSettlement == true)
                            {
                                messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "该订单已结算"));
                                continue;
                            }

                            #endregion

                            #region 3、验证订单明细是否符合结算条件
                            List<T_BAS_OrderDetails> list_orderDetail = query_orderDetail.GetList(a => a.OrderGuid == item.OrderGuid && a.State == DictionaryConst.OrderDetailState.Null);

                            if (list_orderDetail.Count == 0)
                            {
                                messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "找不到与该订单相关联的订单明细"));
                                continue;
                            }
                            #endregion

                            #region 补充 分销赠送积分处理 Bing 151225

                            if (item.PresentExp > 0)
                            {
                                //当前订单下正常&完成所有明细总额
                                var detailSum = list_orderDetail.Sum(c => c.Amount);
                                //对应规则
                                var ruleEntity = new T_INT_IntegralRules()
                                {
                                    IntegralEnable = true,
                                    ProductAmount = item.InProductAmount,
                                    PresentExp = item.InPresentExp
                                };
                                //赠送积分
                                var tempIntegral = 0;
                                IntegralRulesManage.GetIntegral(detailSum, ruleEntity, out tempIntegral);

                                //赠送
                                if (tempIntegral > 0)
                                {
                                    var member = query_member.GetFirstData(c => c.MemberGuid == item.MemberGuid && c.MerchantGuid == item.MerchantGuid, isFilterMerchant: false);
                                    var newIntegral = (member.Integral ?? 0) + tempIntegral;
                                    query_member.Update(c => new object[]
                                    {
                                        c.Integral==newIntegral
                                    }, c => c.MemberGuid == member.MemberGuid && c.MerchantGuid == item.MerchantGuid, isFilterMerchant: false);

                                    query_InTrade.Add(new T_INT_IntegralTrading()
                                       {
                                           IntegralTradingGuid = Guid.NewGuid(),
                                           MemberGuid = member.MemberGuid,
                                           MerchantGuid = member.MerchantGuid,
                                           TradeIntegral = tempIntegral,
                                           IntegralBalance = newIntegral,
                                           OrderGuid = item.OrderGuid,
                                           TradeType = IntegralTradingConst.TradeType.PresentExpType,
                                           TradeDate = DateTime.Now,
                                           IntegralTo = IntegralTradingConst.IntegralToDir.Income
                                       });
                                }
                            }

                            #endregion

                            #region 运费返佣 zhou 2016/4/9
                            decimal firstCommission = 0, secondCommission = 0, thridCommission = 0;
                            if (item.ProductClassify == 3)//零元购只有一个商品
                            {
                                firstCommission = item.FreightFirstCom.Value;
                                secondCommission = item.FreightSecondCom.Value;
                                thridCommission = item.FreightThirdCom.Value;
                            }
                            #endregion

                            #region 4、插入佣金结算记录表并更新分销会员属性表
                            switch (model_distribute.DistributionLevel)
                            {
                                #region 插入佣金结算记录表
                                case DictionaryConst.DistributionLevel.FirstLevel:
                                    #region 一级佣金
                                    //b)	生成订单所属分销商的佣金结算记录（一级佣金），每个订单明细商品生成一条佣金结算记录
                                    try
                                    {
                                        var freightCom = item.Freight.Value * firstCommission;
                                        //一级佣金
                                        foreach (T_BAS_OrderDetails model in list_orderDetail)
                                        {
                                            T_BAS_DistributionCommissions entity = new T_BAS_DistributionCommissions()
                                            {
                                                DistributionCommissionGuid = Guid.NewGuid(),
                                                CommissionAmount = model.FirstCommission + freightCom,
                                                StockDate = DateTime.Now,
                                                MemberGuid = GetMember(model_distribute.DistributionPropGuid.Value),//获取会员Guid
                                                OrderDetailGuid = model.OrderDetailGuid,
                                                DistributeGuid = model_distribute.DistributeGuid,
                                                DistributionPropGuid = model_distribute.DistributionPropGuid,
                                                Level = model_distribute.DistributionLevel,
                                                MerchantGuid = item.MerchantGuid.Value
                                            };
                                            query_distributionCommissions.Add(entity);
                                        }
                                        //更新分销会员属性表
                                        model_prop_first = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.DistributionPropGuid);
                                        if (model_prop_first != null)
                                        {
                                            if (model_prop_first.DistributionCommissions == null)
                                            {
                                                model_prop_first.DistributionCommissions = 0;
                                            }
                                            if (model_prop_first.DistributionAmount == null)
                                            {
                                                model_prop_first.DistributionCommissions = 0;
                                            }
                                            model_prop_first.DistributionCommissions += model_distribute.FirstCommission + freightCom;//分销佣金
                                            model_prop_first.DistributionAmount += item.WXPayMoney ?? item.TotalMoney;//分销金额
                                            query_distributionProp.Update(model_prop_first);
                                        }
                                        #region  模板消息
                                        try
                                        {
                                            if (template != null && model_distribute.FirstCommission != null && model_distribute.FirstCommission.Value > 0)
                                            {
                                                var memberGuid = GetMember(model_distribute.DistributionPropGuid.Value);
                                                string OpenID = memberGuid == null ? "" : MemberManage.GetMemberByGuid(memberGuid.Value).MemberOpenID;
                                                Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                                                send.first = new Wechat.Model.TempateKey("first", "恭喜您，获得了一笔新的佣金，您可以在“我的佣金”中查看详细佣金信息。");
                                                send.keys = new List<Wechat.Model.TempateKey>();
                                                send.keys.Add(new Wechat.Model.TempateKey("orderID", item.OrderNo));
                                                send.keys.Add(new Wechat.Model.TempateKey("keyword1", model_distribute.FirstCommission.Value.ToString("f2")));
                                                send.keys.Add(new Wechat.Model.TempateKey("keyword2", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                                                send.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。");
                                                weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", Common.CurrentManage.MerchantUserID)) + "DistributionCenter/Index", send, Common.CurrentManage.AppId);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Wechat.LogManage.Log("WeiXinSync分销佣金出错:" + ex.Message);
                                        }
                                        #endregion
                                    }
                                    catch (Exception err)
                                    {
                                        messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, err.Message));
                                        continue;
                                    }
                                    #endregion
                                    break;
                                case DictionaryConst.DistributionLevel.SecondLevel:
                                    #region 二级佣金
                                    //c)	如果该分销商存在上级分销商，则生成上级分销商的佣金结算记录（二级佣金），每个订单明细商品生成二条佣金结算记录。
                                    try
                                    {
                                        var freightCom1 = item.Freight.Value * firstCommission;
                                        var freightCom2 = item.Freight.Value * secondCommission;
                                        foreach (T_BAS_OrderDetails model in list_orderDetail)
                                        {
                                            //一级佣金
                                            T_BAS_DistributionCommissions entity_first = new T_BAS_DistributionCommissions()
                                            {
                                                DistributionCommissionGuid = Guid.NewGuid(),
                                                CommissionAmount = model.FirstCommission + freightCom1,
                                                StockDate = DateTime.Now,
                                                MemberGuid = GetMember(model_distribute.DistributionPropGuid.Value),//获取会员Guid
                                                OrderDetailGuid = model.OrderDetailGuid,
                                                DistributeGuid = model.DistributeGuid,
                                                DistributionPropGuid = model_distribute.DistributionPropGuid,
                                                Level = DictionaryConst.DistributionLevel.FirstLevel,
                                                MerchantGuid = item.MerchantGuid.Value
                                            };
                                            //二级佣金
                                            T_BAS_DistributionCommissions entity_second = new T_BAS_DistributionCommissions()
                                            {
                                                DistributionCommissionGuid = Guid.NewGuid(),
                                                CommissionAmount = model.SecondCommission + freightCom2,
                                                StockDate = DateTime.Now,
                                                MemberGuid = GetMember(model_distribute.SuperiorDistributorGuid.Value),
                                                OrderDetailGuid = model.OrderDetailGuid,
                                                DistributeGuid = model.DistributeGuid,
                                                DistributionPropGuid = model_distribute.SuperiorDistributorGuid,
                                                Level = DictionaryConst.DistributionLevel.SecondLevel,
                                                MerchantGuid = item.MerchantGuid.Value
                                            };
                                            //合计分销佣金
                                            query_distributionCommissions.Add(entity_first);
                                            query_distributionCommissions.Add(entity_second);
                                        }
                                        //更新分销会员属性表
                                        //一级
                                        model_prop_first = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.DistributionPropGuid);
                                        model_prop_second = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.SuperiorDistributorGuid);
                                        if (model_prop_first != null)
                                        {
                                            if (model_prop_first.DistributionCommissions == null)
                                            {
                                                model_prop_first.DistributionCommissions = 0;
                                            }
                                            if (model_prop_first.DistributionAmount == null)
                                            {
                                                model_prop_first.DistributionCommissions = 0;
                                            }
                                            model_prop_first.DistributionCommissions += model_distribute.FirstCommission + freightCom1;//分销佣金
                                            model_prop_first.DistributionAmount += item.WXPayMoney ?? item.TotalMoney;//分销金额
                                            query_distributionProp.Update(model_prop_first);
                                        }
                                        //二级
                                        if (model_prop_second != null)
                                        {
                                            if (model_prop_second.DistributionCommissions == null)
                                            {
                                                model_prop_second.DistributionCommissions = 0;
                                            }
                                            if (model_prop_second.DistributionAmount == null)
                                            {
                                                model_prop_second.DistributionCommissions = 0;
                                            }
                                            model_prop_second.DistributionCommissions += model_distribute.SecondCommission + freightCom2;//分销佣金
                                            model_prop_second.DistributionAmount += item.WXPayMoney ?? item.TotalMoney;//分销金额
                                            query_distributionProp.Update(model_prop_second);
                                        }



                                        #region  模板消息
                                        try
                                        {
                                            if (template != null)
                                            {
                                                if (model_distribute.DistributionPropGuid != null && model_distribute.FirstCommission != null && model_distribute.FirstCommission.Value > 0)
                                                {
                                                    var memberGuid = GetMember(model_distribute.DistributionPropGuid.Value);
                                                    string OpenID = memberGuid == null ? "" : MemberManage.GetMemberByGuid(memberGuid.Value).MemberOpenID;

                                                    Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                                                    send.first = new Wechat.Model.TempateKey("first", "恭喜您，获得了一笔新的佣金，您可以在“我的佣金”中查看详细佣金信息。");
                                                    send.keys = new List<Wechat.Model.TempateKey>();
                                                    send.keys.Add(new Wechat.Model.TempateKey("orderID", item.OrderNo));
                                                    send.keys.Add(new Wechat.Model.TempateKey("keyword1", model_distribute.FirstCommission.Value.ToString("f2")));
                                                    send.keys.Add(new Wechat.Model.TempateKey("keyword2", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                                                    send.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", Common.CurrentManage.MerchantUserID)) + "DistributionCenter/Index", send, Common.CurrentManage.AppId);
                                                }
                                                if (model_distribute.SuperiorDistributorGuid != null && model_distribute.SecondCommission != null && model_distribute.SecondCommission.Value > 0)
                                                {
                                                    var superiorMemberGuid = GetMember(model_distribute.SuperiorDistributorGuid.Value);
                                                    string SupOpenID = superiorMemberGuid == null ? "" : MemberManage.GetMemberByGuid(superiorMemberGuid.Value).MemberOpenID;
                                                    Wechat.Model.SendTempateKey sendSup = new Wechat.Model.SendTempateKey();
                                                    sendSup.first = new Wechat.Model.TempateKey("first", "恭喜您，获得了一笔新的佣金，您可以在“我的佣金”中查看详细佣金信息。");
                                                    sendSup.keys = new List<Wechat.Model.TempateKey>();
                                                    sendSup.keys.Add(new Wechat.Model.TempateKey("orderID", item.OrderNo));
                                                    sendSup.keys.Add(new Wechat.Model.TempateKey("keyword1", model_distribute.SecondCommission.Value.ToString("f2")));
                                                    sendSup.keys.Add(new Wechat.Model.TempateKey("keyword2", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                                                    sendSup.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(SupOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", Common.CurrentManage.MerchantUserID)) + "DistributionCenter/Index", sendSup, Common.CurrentManage.AppId);
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Wechat.LogManage.Log("WeiXinSync分销佣金出错:" + ex.Message);
                                        }
                                        #endregion
                                    }
                                    catch (Exception err)
                                    {
                                        messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, err.Message));
                                        continue;
                                    }
                                    #endregion
                                    break;
                                case DictionaryConst.DistributionLevel.ThirdLevel:
                                    #region 三级佣金
                                    //d)	如果该分销商存在上上级分销商，则生成上上级分销商的佣金结算记录（三级佣金），每个订单明细商品生成三条佣金结算记录。
                                    try
                                    {
                                        var freightCom1 = item.Freight.Value * firstCommission;
                                        var freightCom2 = item.Freight.Value * secondCommission;
                                        var freightCom3 = item.Freight.Value * thridCommission;
                                        foreach (T_BAS_OrderDetails model in list_orderDetail)
                                        {
                                            //一级佣金
                                            T_BAS_DistributionCommissions entity_one = new T_BAS_DistributionCommissions()
                                            {
                                                DistributionCommissionGuid = Guid.NewGuid(),
                                                CommissionAmount = model.FirstCommission + freightCom1,
                                                StockDate = DateTime.Now,
                                                MemberGuid = GetMember(model_distribute.DistributionPropGuid.Value),//获取会员Guid
                                                OrderDetailGuid = model.OrderDetailGuid,
                                                DistributeGuid = model.DistributeGuid,
                                                DistributionPropGuid = model_distribute.DistributionPropGuid,
                                                Level = DictionaryConst.DistributionLevel.FirstLevel,
                                                MerchantGuid = item.MerchantGuid.Value
                                            };
                                            //二级佣金
                                            T_BAS_DistributionCommissions entity_two = new T_BAS_DistributionCommissions()
                                            {
                                                DistributionCommissionGuid = Guid.NewGuid(),
                                                CommissionAmount = model.SecondCommission + freightCom2,
                                                StockDate = DateTime.Now,
                                                MemberGuid = GetMember(model_distribute.SuperiorDistributorGuid.Value),
                                                OrderDetailGuid = model.OrderDetailGuid,
                                                DistributeGuid = model.DistributeGuid,
                                                DistributionPropGuid = model_distribute.SuperiorDistributorGuid,
                                                Level = DictionaryConst.DistributionLevel.SecondLevel,
                                                MerchantGuid = item.MerchantGuid.Value
                                            };
                                            //三级佣金
                                            T_BAS_DistributionCommissions entity_three = new T_BAS_DistributionCommissions()
                                            {
                                                DistributionCommissionGuid = Guid.NewGuid(),
                                                CommissionAmount = model.ThirdCommission + freightCom3,
                                                StockDate = DateTime.Now,
                                                MemberGuid = GetMember(model_distribute.TopDistributorGuid.Value),
                                                OrderDetailGuid = model.OrderDetailGuid,
                                                DistributeGuid = model.DistributeGuid,
                                                DistributionPropGuid = model_distribute.TopDistributorGuid,
                                                Level = DictionaryConst.DistributionLevel.ThirdLevel,
                                                MerchantGuid = item.MerchantGuid.Value
                                            };
                                            query_distributionCommissions.Add(entity_one);
                                            query_distributionCommissions.Add(entity_two);
                                            query_distributionCommissions.Add(entity_three);
                                        }
                                        //更新分销会员属性表
                                        model_prop_first = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.DistributionPropGuid.Value);
                                        model_prop_second = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.SuperiorDistributorGuid.Value);
                                        model_prop_third = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.TopDistributorGuid.Value);
                                        if (model_prop_first != null)
                                        {
                                            if (model_prop_first.DistributionCommissions == null)
                                            {
                                                model_prop_first.DistributionCommissions = 0;
                                            }
                                            if (model_prop_first.DistributionAmount == null)
                                            {
                                                model_prop_first.DistributionCommissions = 0;
                                            }
                                            model_prop_first.DistributionCommissions += model_distribute.FirstCommission + freightCom1;//分销佣金
                                            model_prop_first.DistributionAmount += item.WXPayMoney ?? item.TotalMoney;//分销金额
                                            query_distributionProp.Update(model_prop_first);
                                        }
                                        //二级
                                        if (model_prop_second != null)
                                        {
                                            if (model_prop_second.DistributionCommissions == null)
                                            {
                                                model_prop_second.DistributionCommissions = 0;
                                            }
                                            if (model_prop_second.DistributionAmount == null)
                                            {
                                                model_prop_second.DistributionCommissions = 0;
                                            }
                                            model_prop_second.DistributionCommissions += model_distribute.SecondCommission + freightCom2;//分销佣金
                                            model_prop_second.DistributionAmount += item.WXPayMoney ?? item.TotalMoney;//分销金额
                                            query_distributionProp.Update(model_prop_second);
                                        }
                                        //三级
                                        if (model_prop_third != null)
                                        {
                                            if (model_prop_third.DistributionCommissions == null)
                                            {
                                                model_prop_third.DistributionCommissions = 0;
                                            }
                                            if (model_prop_third.DistributionAmount == null)
                                            {
                                                model_prop_third.DistributionCommissions = 0;
                                            }
                                            model_prop_third.DistributionCommissions += model_distribute.ThirdCommission + freightCom3;//分销佣金
                                            model_prop_third.DistributionAmount += item.WXPayMoney ?? item.TotalMoney;//分销金额
                                            query_distributionProp.Update(model_prop_third);
                                        }
                                        #region  模板消息
                                        try
                                        {
                                            if (template != null)
                                            {

                                                if (model_distribute.DistributionPropGuid != null && model_distribute.FirstCommission != null && model_distribute.FirstCommission.Value > 0)
                                                {
                                                    var memberGuid = GetMember(model_distribute.DistributionPropGuid.Value);
                                                    string OpenID = memberGuid == null ? "" : MemberManage.GetMemberByGuid(memberGuid.Value).MemberOpenID;

                                                    Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                                                    send.first = new Wechat.Model.TempateKey("first", "恭喜您，获得了一笔新的佣金，您可以在“我的佣金”中查看详细佣金信息。");
                                                    send.keys = new List<Wechat.Model.TempateKey>();
                                                    send.keys.Add(new Wechat.Model.TempateKey("orderID", item.OrderNo));
                                                    send.keys.Add(new Wechat.Model.TempateKey("keyword1", model_distribute.FirstCommission.Value.ToString("f2")));
                                                    send.keys.Add(new Wechat.Model.TempateKey("keyword2", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                                                    send.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", Common.CurrentManage.MerchantUserID)) + "DistributionCenter/Index", send, Common.CurrentManage.AppId);
                                                }
                                                if (model_distribute.SuperiorDistributorGuid != null && model_distribute.SecondCommission != null && model_distribute.SecondCommission.Value > 0)
                                                {
                                                    var superiorMemberGuid = GetMember(model_distribute.SuperiorDistributorGuid.Value);
                                                    string SupOpenID = superiorMemberGuid == null ? "" : MemberManage.GetMemberByGuid(superiorMemberGuid.Value).MemberOpenID;
                                                    Wechat.Model.SendTempateKey sendSup = new Wechat.Model.SendTempateKey();
                                                    sendSup.first = new Wechat.Model.TempateKey("first", "恭喜您，获得了一笔新的佣金，您可以在“我的佣金”中查看详细佣金信息。");
                                                    sendSup.keys = new List<Wechat.Model.TempateKey>();
                                                    sendSup.keys.Add(new Wechat.Model.TempateKey("orderID", item.OrderNo));
                                                    sendSup.keys.Add(new Wechat.Model.TempateKey("keyword1", model_distribute.SecondCommission.Value.ToString("f2")));
                                                    sendSup.keys.Add(new Wechat.Model.TempateKey("keyword2", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                                                    sendSup.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(SupOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", Common.CurrentManage.MerchantUserID)) + "DistributionCenter/Index", sendSup, Common.CurrentManage.AppId);
                                                }
                                                if (model_distribute.TopDistributorGuid != null && model_distribute.ThirdCommission != null && model_distribute.ThirdCommission.Value > 0)
                                                {
                                                    var topMemberGuid = GetMember(model_distribute.TopDistributorGuid.Value);
                                                    string TopOpenID = topMemberGuid == null ? "" : MemberManage.GetMemberByGuid(topMemberGuid.Value).MemberOpenID;

                                                    Wechat.Model.SendTempateKey sendTop = new Wechat.Model.SendTempateKey();
                                                    sendTop.first = new Wechat.Model.TempateKey("first", "恭喜您，获得了一笔新的佣金，您可以在“我的佣金”中查看详细佣金信息。");
                                                    sendTop.keys = new List<Wechat.Model.TempateKey>();
                                                    sendTop.keys.Add(new Wechat.Model.TempateKey("orderID", item.OrderNo));
                                                    sendTop.keys.Add(new Wechat.Model.TempateKey("keyword1", model_distribute.ThirdCommission.Value.ToString("f2")));
                                                    sendTop.keys.Add(new Wechat.Model.TempateKey("keyword2", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                                                    sendTop.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(TopOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", Common.CurrentManage.MerchantUserID)) + "DistributionCenter/Index", sendTop, Common.CurrentManage.AppId);
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Wechat.LogManage.Log("WeiXinSync分销佣金出错:" + ex.Message);
                                        }
                                        #endregion

                                    }
                                    catch (Exception err)
                                    {
                                        messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, err.Message));
                                        continue;
                                    }
                                    #endregion
                                    break;
                                #endregion
                            }
                            #endregion

                            #region 5、更新分销订单属性表
                            //更新分销订单属性表
                            try
                            {
                                model_distribute.IsSettlement = true;
                                model_distribute.SettlementDate = DateTime.Now;
                                query_distribute.Update(model_distribute);
                            }
                            catch (Exception err)
                            {
                                messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, err.Message));
                                continue;
                            }
                            #endregion
                        }
                        #region 6、更新商家表
                        //更新商家表
                        try
                        {
                            List<T_BAS_WithdrawsCommission> list_withdrawsCommission = query_withdrawsCommission.GetList(a => a.MerchantGuid == Common.CurrentManage.MerchantGuid.ToString() && a.State == DictionaryConst.WithdriwalCom.WithdrawalsSuccess);
                            if (merchant != null)
                            {
                                if (merchant.TotalDistributionOrders == null)
                                {
                                    merchant.TotalDistributionOrders = 0;
                                }
                                if (merchant.DistributionOrdersAmount == null)
                                {
                                    merchant.DistributionOrdersAmount = 0;
                                }
                                if (merchant.TotalDistributor == null)
                                {
                                    merchant.TotalDistributor = 0;
                                }
                                if (merchant.CumulativeDistributionAmount == null)
                                {
                                    merchant.CumulativeDistributionAmount = 0;
                                }
                                //var list_distributeOrder = query_distributeOrder.GetList(a => a.MerchantGuid == merchant.MerchantGuid);
                                ///处理运费返佣 zhou 2016/4/6 
                                var list_distributeOrder = Factory.CreateProcedure(tran).Get_Distribution_Order(merchant.MerchantGuid);
                                if (list_distributeOrder.Count > 0)
                                {
                                    merchant.TotalDistributionOrders = list_distributeOrder.Count();
                                    merchant.DistributionOrdersAmount = list_distributeOrder.Sum(a => a.TotalMoney);
                                    merchant.TotalDistributor = query_distributionProp.GetCount(a => a.IsEnable == true);
                                    merchant.CumulativeDistributionAmount = list_distributeOrder.Sum(a => a.TotalCommission);
                                }
                                if (list_withdrawsCommission.Count > 0)
                                {
                                    var applymount = list_withdrawsCommission.Sum(a => a.ApplyAmount);
                                    merchant.MentionedAmount = applymount == null ? 0 : applymount.Value;
                                }
                                else
                                {
                                    merchant.MentionedAmount = 0;
                                }
                                query_merchant.Update(merchant, false);

                            }

                        }
                        catch (Exception err)
                        {
                            messageBox.Add(new MessageBox(false, merchant.StoreTitle, err.Message));
                        }
                        #endregion



                    }
                    catch (Exception err)
                    {
                        messageBox.Add(new MessageBox(false, err.Message));
                        return new Result(false, err.Message);
                    }

                    //补充：总部订单积分赠送处理(手动) Bing 160121
                    ExtHqOrderPresentExp(tran, Common.CurrentManage.MerchantGuid, query_member, query_InTrade, query_order);

                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception err)
                {
                    tran.Rollback();
                    return new Result(false, err.Message);
                }


            }

        }
        #endregion

        #region 单订单结算佣金
        public static Result GetTotalAmount(Guid merchantGuid, Guid orderGuid, string appid)
        {
            List<MessageBox> messageBox = new List<MessageBox>();
            string msg = "";
            //分销佣金
            using (var tran = new SqlRTransaction())
            {
                var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                var querywechat = Factory.CreateT_WX_WeChat(tran);
                var merchGuid = HeadPay.GetPayMerchantGuid(CurrentManage.MerchantUserID);
                var template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.佣金提醒, isFilterMerchant: false);
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_parameter = Factory.CreateT_SYS_Parameter(tran);
                var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                var query_distributionProp = Factory.CreateT_BAS_DistributionProp(tran);
                var query_distributionCommissions = Factory.CreateT_BAS_DistributionCommissions(tran);
                var query_distribute = Factory.CreateT_BAS_Distribute(tran);
                var query_merchant = Factory.CreateT_BAS_Merchants(tran);
                var query_member = Factory.CreateT_BAS_Member(tran);

                var query_product = Factory.CreateProcedure(tran);
                var query_distributeOrder = Factory.CreateT_ST_DistributeOrder(tran);
                var query_InTrade = Factory.CreateT_INT_IntegralTrading(tran);
                var merchant = query_merchant.GetFirstData(a => a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                T_BAS_DistributionProp model_prop_first = null;
                T_BAS_DistributionProp model_prop_second = null;
                T_BAS_DistributionProp model_prop_third = null;
                try
                {
                    T_BAS_Orders order = query_order.GetFirstData(a => a.OrderGuid == orderGuid && a.IsDistribute == true && a.OrderState == DictionaryConst.OrderState.Completed && a.MerchantGuid == merchantGuid, false, null, OrderMethods.Default, LockType.Default, false);
                    if (order == null) return new Result(false, "没有满足条件的分销订单需结算！");
                    #region 1、验证参数
                    T_SYS_Parameter model_parameter = query_parameter.GetFirstData(a => a.ParameterName == ParameterName.CommissionMember.CommissionSettlementTime && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                    if (model_parameter == null)
                    {
                        return new Result(false, "未设置佣金结算时间");
                    }
                    T_SYS_Parameter model_parameter_firstCommission = query_parameter.GetFirstData(a => a.ParameterName == ParameterName.CommissionMember.FirstCommission && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                    if (model_parameter_firstCommission == null)
                    {
                        return new Result(false, "未设置一级佣金结算比例");
                    }
                    T_SYS_Parameter model_parameter_secondCommission = query_parameter.GetFirstData(a => a.ParameterName == ParameterName.CommissionMember.SecondCommission && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                    if (model_parameter_secondCommission == null)
                    {
                        return new Result(false, "未设置二级佣金结算比例");
                    }
                    T_SYS_Parameter model_parameter_thirdCommission = query_parameter.GetFirstData(a => a.ParameterName == ParameterName.CommissionMember.ThirdCommission && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                    if (model_parameter_thirdCommission == null)
                    {
                        return new Result(false, "未设置三级佣金结算比例");
                    }
                    #endregion
                    try
                    {
                        //2.	结算逻辑：
                        //a)	符合条件的分销订单：订单完成时间+参数030204>当前时间 

                        if (order.CompletedTime == null) return new Result(false, "该订单尚未结算！");
                        if ((DateTimeEx.DateDiff(order.CompletedTime.Value) < int.Parse(model_parameter.ParameterValue) && int.Parse(model_parameter.ParameterValue) != 0)) return new Result(false, "该订单不满足佣金结算时间限制！");

                        #region 2、验证分销订单是否符合结算条件
                        var model_distribute = query_distribute.GetFirstData(a => a.OrderGuid == orderGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);
                        //是否有分销订单
                        if (model_distribute == null) return new Result(false, "找不到与该订单相关联的分销订单！");
                        if (model_distribute.CompletionDate == null) return new Result(false, "该分销订单尚未完成！");
                        //分销订单是否已结算
                        if (model_distribute.IsSettlement == true) return new Result(false, "该订单已结算！");

                        #endregion

                        #region 3、验证订单明细是否符合结算条件
                        List<T_BAS_OrderDetails> list_orderDetail = query_orderDetail.GetList(a => a.OrderGuid == orderGuid && a.State == DictionaryConst.OrderDetailState.Null, isFilterMerchant: false);
                        if (list_orderDetail.Count == 0) return new Result(false, "找不到与该订单相关联的订单明细！");
                        #endregion

                        tran.BeginTransaction();
                        #region 补充 分销赠送积分处理 Bing 151225

                        if (order.PresentExp > 0)
                        {
                            //当前订单下正常&完成所有明细总额
                            var detailSum = list_orderDetail.Sum(c => c.Amount);
                            //对应规则
                            var ruleEntity = new T_INT_IntegralRules()
                            {
                                IntegralEnable = true,
                                ProductAmount = order.InProductAmount,
                                PresentExp = order.InPresentExp
                            };
                            //赠送积分
                            var tempIntegral = 0;
                            IntegralRulesManage.GetIntegral(detailSum, ruleEntity, out tempIntegral);

                            //赠送
                            if (tempIntegral > 0)
                            {
                                var member = query_member.GetFirstData(c => c.MemberGuid == order.MemberGuid && c.MerchantGuid == order.MerchantGuid, isFilterMerchant: false);
                                var newIntegral = (member.Integral ?? 0) + tempIntegral;
                                query_member.Update(c => new object[]
                                {
                                    c.Integral==newIntegral
                                }, c => c.MemberGuid == member.MemberGuid && c.MerchantGuid == order.MerchantGuid, isFilterMerchant: false);

                                query_InTrade.Add(new T_INT_IntegralTrading()
                                {
                                    IntegralTradingGuid = Guid.NewGuid(),
                                    MemberGuid = member.MemberGuid,
                                    MerchantGuid = member.MerchantGuid,
                                    TradeIntegral = tempIntegral,
                                    IntegralBalance = newIntegral,
                                    OrderGuid = orderGuid,
                                    TradeType = IntegralTradingConst.TradeType.PresentExpType,
                                    TradeDate = DateTime.Now,
                                    IntegralTo = IntegralTradingConst.IntegralToDir.Income
                                });
                            }
                        }

                        #endregion

                        #region 4、插入佣金结算记录表并更新分销会员属性表
                        switch (model_distribute.DistributionLevel)
                        {
                            #region 插入佣金结算记录表
                            case DictionaryConst.DistributionLevel.FirstLevel:
                                #region 一级佣金
                                //b)	生成订单所属分销商的佣金结算记录（一级佣金），每个订单明细商品生成一条佣金结算记录
                                try
                                {
                                    //一级佣金
                                    foreach (T_BAS_OrderDetails model in list_orderDetail)
                                    {
                                        T_BAS_DistributionCommissions entity = new T_BAS_DistributionCommissions()
                                        {
                                            DistributionCommissionGuid = Guid.NewGuid(),
                                            CommissionAmount = model.FirstCommission,
                                            StockDate = DateTime.Now,
                                            MemberGuid = GetMember(model_distribute.DistributionPropGuid.Value),//获取会员Guid
                                            OrderDetailGuid = model.OrderDetailGuid,
                                            DistributeGuid = model_distribute.DistributeGuid,
                                            DistributionPropGuid = model_distribute.DistributionPropGuid,
                                            Level = model_distribute.DistributionLevel,
                                            MerchantGuid = order.MerchantGuid.Value
                                        };
                                        query_distributionCommissions.Add(entity);
                                    }
                                    //更新分销会员属性表
                                    model_prop_first = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.DistributionPropGuid, isFilterMerchant: false);
                                    if (model_prop_first != null)
                                    {
                                        if (model_prop_first.DistributionCommissions == null)
                                        {
                                            model_prop_first.DistributionCommissions = 0;
                                        }
                                        if (model_prop_first.DistributionAmount == null)
                                        {
                                            model_prop_first.DistributionCommissions = 0;
                                        }
                                        model_prop_first.DistributionCommissions += model_distribute.FirstCommission;//分销佣金
                                        model_prop_first.DistributionAmount += order.WXPayMoney ?? order.TotalMoney;//分销金额
                                        query_distributionProp.Update(model_prop_first, false);
                                    }
                                    #region  模板消息
                                    if (template != null && model_distribute.FirstCommission != null && model_distribute.FirstCommission.Value > 0)
                                    {
                                        var memberGuid = GetMember(model_distribute.DistributionPropGuid.Value);
                                        string openid = memberGuid == null ? "" : MemberManage.GetMemberByGuid(memberGuid.Value).MemberOpenID;
                                        decimal firstCommission = model_distribute.FirstCommission.Value;
                                        MessageTemplateManage.SendMessage_Commission(merchant.UserID, template.TemplateID, openid, order.OrderNo, firstCommission, appid);
                                    }
                                    #endregion
                                }
                                catch (Exception err)
                                {
                                    return new Result(false, err.Message);
                                }
                                #endregion
                                break;
                            case DictionaryConst.DistributionLevel.SecondLevel:
                                #region 二级佣金
                                //c)	如果该分销商存在上级分销商，则生成上级分销商的佣金结算记录（二级佣金），每个订单明细商品生成二条佣金结算记录。
                                try
                                {
                                    foreach (T_BAS_OrderDetails model in list_orderDetail)
                                    {
                                        //一级佣金
                                        T_BAS_DistributionCommissions entity_first = new T_BAS_DistributionCommissions()
                                        {
                                            DistributionCommissionGuid = Guid.NewGuid(),
                                            CommissionAmount = model.FirstCommission,
                                            StockDate = DateTime.Now,
                                            MemberGuid = GetMember(model_distribute.DistributionPropGuid.Value),//获取会员Guid
                                            OrderDetailGuid = model.OrderDetailGuid,
                                            DistributeGuid = model.DistributeGuid,
                                            DistributionPropGuid = model_distribute.DistributionPropGuid,
                                            Level = DictionaryConst.DistributionLevel.FirstLevel,
                                            MerchantGuid = order.MerchantGuid.Value
                                        };
                                        //二级佣金
                                        T_BAS_DistributionCommissions entity_second = new T_BAS_DistributionCommissions()
                                        {
                                            DistributionCommissionGuid = Guid.NewGuid(),
                                            CommissionAmount = model.SecondCommission,
                                            StockDate = DateTime.Now,
                                            MemberGuid = GetMember(model_distribute.SuperiorDistributorGuid.Value),
                                            OrderDetailGuid = model.OrderDetailGuid,
                                            DistributeGuid = model.DistributeGuid,
                                            DistributionPropGuid = model_distribute.SuperiorDistributorGuid,
                                            Level = DictionaryConst.DistributionLevel.SecondLevel,
                                            MerchantGuid = order.MerchantGuid.Value
                                        };
                                        //合计分销佣金
                                        query_distributionCommissions.Add(entity_first);
                                        query_distributionCommissions.Add(entity_second);
                                    }
                                    //更新分销会员属性表
                                    //一级
                                    model_prop_first = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.DistributionPropGuid);
                                    model_prop_second = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.SuperiorDistributorGuid);
                                    if (model_prop_first != null)
                                    {
                                        if (model_prop_first.DistributionCommissions == null)
                                        {
                                            model_prop_first.DistributionCommissions = 0;
                                        }
                                        if (model_prop_first.DistributionAmount == null)
                                        {
                                            model_prop_first.DistributionCommissions = 0;
                                        }
                                        model_prop_first.DistributionCommissions += model_distribute.FirstCommission;//分销佣金
                                        model_prop_first.DistributionAmount += order.WXPayMoney ?? order.TotalMoney;//分销金额
                                        query_distributionProp.Update(model_prop_first);
                                    }
                                    //二级
                                    if (model_prop_second != null)
                                    {
                                        if (model_prop_second.DistributionCommissions == null)
                                        {
                                            model_prop_second.DistributionCommissions = 0;
                                        }
                                        if (model_prop_second.DistributionAmount == null)
                                        {
                                            model_prop_second.DistributionCommissions = 0;
                                        }
                                        model_prop_second.DistributionCommissions += model_distribute.SecondCommission;//分销佣金
                                        model_prop_second.DistributionAmount += order.WXPayMoney ?? order.TotalMoney;//分销金额
                                        query_distributionProp.Update(model_prop_second);
                                    }
                                    #region  模板消息
                                    if (template != null)
                                    {
                                        if (model_distribute.DistributionPropGuid != null && model_distribute.FirstCommission != null && model_distribute.FirstCommission.Value > 0)
                                        {
                                            var memberGuid = GetMember(model_distribute.DistributionPropGuid.Value);
                                            string openid = memberGuid == null ? "" : MemberManage.GetMemberByGuid(memberGuid.Value).MemberOpenID;
                                            decimal firstCommission = model_distribute.FirstCommission.Value;
                                            MessageTemplateManage.SendMessage_Commission(merchant.UserID, template.TemplateID, openid, order.OrderNo, firstCommission, appid);
                                        }
                                        if (model_distribute.SuperiorDistributorGuid != null && model_distribute.SecondCommission != null && model_distribute.SecondCommission.Value > 0)
                                        {
                                            var superiorMemberGuid = GetMember(model_distribute.SuperiorDistributorGuid.Value);
                                            string supOpenID = superiorMemberGuid == null ? "" : MemberManage.GetMemberByGuid(superiorMemberGuid.Value).MemberOpenID;
                                            decimal secondCommission = model_distribute.SecondCommission.Value;
                                            MessageTemplateManage.SendMessage_Commission(merchant.UserID, template.TemplateID, supOpenID, order.OrderNo, secondCommission, appid);
                                        }
                                    }
                                    #endregion
                                }
                                catch (Exception err)
                                {
                                    return new Result(false, err.Message);
                                }
                                #endregion
                                break;
                            case DictionaryConst.DistributionLevel.ThirdLevel:
                                #region 三级佣金
                                //d)	如果该分销商存在上上级分销商，则生成上上级分销商的佣金结算记录（三级佣金），每个订单明细商品生成三条佣金结算记录。
                                try
                                {
                                    foreach (T_BAS_OrderDetails model in list_orderDetail)
                                    {
                                        //一级佣金
                                        T_BAS_DistributionCommissions entity_one = new T_BAS_DistributionCommissions()
                                        {
                                            DistributionCommissionGuid = Guid.NewGuid(),
                                            CommissionAmount = model.FirstCommission,
                                            StockDate = DateTime.Now,
                                            MemberGuid = GetMember(model_distribute.DistributionPropGuid.Value),//获取会员Guid
                                            OrderDetailGuid = model.OrderDetailGuid,
                                            DistributeGuid = model.DistributeGuid,
                                            DistributionPropGuid = model_distribute.DistributionPropGuid,
                                            Level = DictionaryConst.DistributionLevel.FirstLevel,
                                            MerchantGuid = order.MerchantGuid.Value
                                        };
                                        //二级佣金
                                        T_BAS_DistributionCommissions entity_two = new T_BAS_DistributionCommissions()
                                        {
                                            DistributionCommissionGuid = Guid.NewGuid(),
                                            CommissionAmount = model.SecondCommission,
                                            StockDate = DateTime.Now,
                                            MemberGuid = GetMember(model_distribute.SuperiorDistributorGuid.Value),
                                            OrderDetailGuid = model.OrderDetailGuid,
                                            DistributeGuid = model.DistributeGuid,
                                            DistributionPropGuid = model_distribute.SuperiorDistributorGuid,
                                            Level = DictionaryConst.DistributionLevel.SecondLevel,
                                            MerchantGuid = order.MerchantGuid.Value
                                        };
                                        //三级佣金
                                        T_BAS_DistributionCommissions entity_three = new T_BAS_DistributionCommissions()
                                        {
                                            DistributionCommissionGuid = Guid.NewGuid(),
                                            CommissionAmount = model.ThirdCommission,
                                            StockDate = DateTime.Now,
                                            MemberGuid = GetMember(model_distribute.TopDistributorGuid.Value),
                                            OrderDetailGuid = model.OrderDetailGuid,
                                            DistributeGuid = model.DistributeGuid,
                                            DistributionPropGuid = model_distribute.TopDistributorGuid,
                                            Level = DictionaryConst.DistributionLevel.ThirdLevel,
                                            MerchantGuid = order.MerchantGuid.Value
                                        };
                                        query_distributionCommissions.Add(entity_one);
                                        query_distributionCommissions.Add(entity_two);
                                        query_distributionCommissions.Add(entity_three);
                                    }
                                    //更新分销会员属性表
                                    model_prop_first = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.DistributionPropGuid.Value);
                                    model_prop_second = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.SuperiorDistributorGuid.Value);
                                    model_prop_third = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.TopDistributorGuid.Value);
                                    if (model_prop_first != null)
                                    {
                                        if (model_prop_first.DistributionCommissions == null)
                                        {
                                            model_prop_first.DistributionCommissions = 0;
                                        }
                                        if (model_prop_first.DistributionAmount == null)
                                        {
                                            model_prop_first.DistributionCommissions = 0;
                                        }
                                        model_prop_first.DistributionCommissions += model_distribute.FirstCommission;//分销佣金
                                        model_prop_first.DistributionAmount += order.WXPayMoney ?? order.TotalMoney;//分销金额
                                        query_distributionProp.Update(model_prop_first);
                                    }
                                    //二级
                                    if (model_prop_second != null)
                                    {
                                        if (model_prop_second.DistributionCommissions == null)
                                        {
                                            model_prop_second.DistributionCommissions = 0;
                                        }
                                        if (model_prop_second.DistributionAmount == null)
                                        {
                                            model_prop_second.DistributionCommissions = 0;
                                        }
                                        model_prop_second.DistributionCommissions += model_distribute.SecondCommission;//分销佣金
                                        model_prop_second.DistributionAmount += order.WXPayMoney ?? order.TotalMoney;//分销金额
                                        query_distributionProp.Update(model_prop_second);
                                    }
                                    //三级
                                    if (model_prop_third != null)
                                    {
                                        if (model_prop_third.DistributionCommissions == null)
                                        {
                                            model_prop_third.DistributionCommissions = 0;
                                        }
                                        if (model_prop_third.DistributionAmount == null)
                                        {
                                            model_prop_third.DistributionCommissions = 0;
                                        }
                                        model_prop_third.DistributionCommissions += model_distribute.ThirdCommission;//分销佣金
                                        model_prop_third.DistributionAmount += order.WXPayMoney ?? order.TotalMoney;//分销金额
                                        query_distributionProp.Update(model_prop_third);
                                    }
                                    #region  模板消息
                                    if (template != null)
                                    {
                                        if (template != null)
                                        {
                                            if (model_distribute.DistributionPropGuid != null && model_distribute.FirstCommission != null && model_distribute.FirstCommission.Value > 0)
                                            {
                                                var memberGuid = GetMember(model_distribute.DistributionPropGuid.Value);
                                                string openid = memberGuid == null ? "" : MemberManage.GetMemberByGuid(memberGuid.Value).MemberOpenID;
                                                decimal firstCommission = model_distribute.FirstCommission.Value;
                                                MessageTemplateManage.SendMessage_Commission(merchant.UserID, template.TemplateID, openid, order.OrderNo, firstCommission, appid);
                                            }
                                            if (model_distribute.SuperiorDistributorGuid != null && model_distribute.SecondCommission != null && model_distribute.SecondCommission.Value > 0)
                                            {
                                                var superiorMemberGuid = GetMember(model_distribute.SuperiorDistributorGuid.Value);
                                                string supOpenID = superiorMemberGuid == null ? "" : MemberManage.GetMemberByGuid(superiorMemberGuid.Value).MemberOpenID;
                                                decimal secondCommission = model_distribute.SecondCommission.Value;
                                                MessageTemplateManage.SendMessage_Commission(merchant.UserID, template.TemplateID, supOpenID, order.OrderNo, secondCommission, appid);
                                            }
                                            if (model_distribute.TopDistributorGuid != null && model_distribute.ThirdCommission != null && model_distribute.ThirdCommission.Value > 0)
                                            {
                                                var topMemberGuid = GetMember(model_distribute.TopDistributorGuid.Value);
                                                string topOpenID = topMemberGuid == null ? "" : MemberManage.GetMemberByGuid(topMemberGuid.Value).MemberOpenID;
                                                decimal thirdCommission = model_distribute.ThirdCommission.Value;
                                                MessageTemplateManage.SendMessage_Commission(merchant.UserID, template.TemplateID, topOpenID, order.OrderNo, thirdCommission, appid);
                                            }
                                        }
                                    }
                                    #endregion
                                }
                                catch (Exception err)
                                {
                                    return new Result(false, err.Message);
                                }
                                #endregion
                                break;
                            #endregion
                        }
                        #endregion

                        #region 5、更新分销订单表
                        //更新分销订单表
                        model_distribute.IsSettlement = true;
                        model_distribute.SettlementDate = DateTime.Now;
                        Result result_distribute = UpdateDistributionOrder(tran, query_distribute, model_distribute);
                        if (!result_distribute.State) return new Result(false, "更新分销订单出错！");
                        #endregion

                        #region 6、更新商家表
                        //更新商家表
                        Result result_merchant = MerchantManage.UpdateTotalOrders(tran, query_distributeOrder, query_distributionProp, query_merchant, merchant);
                        if (!result_merchant.State) return new Result(false, "更新商家出错！");
                        #endregion

                    }
                    catch (Exception err)
                    {
                        return new Result(false, err.Message);
                    }
                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception err)
                {
                    tran.Rollback();
                    return new Result(false, err.Message);
                }
            }

        }
        #endregion

        #region 结算分销佣金(自动)
        public static Result GetAmount()
        {
            List<MessageBox> messageBox = new List<MessageBox>();
            var querymerchant = Factory.CreateT_BAS_Merchants();
            var list_merchant = querymerchant.GetList(a => a.StoreState == true, true, null, OrderMethods.Default, LockType.Default, false);
            querymerchant.Dispose();
            T_BAS_DistributionProp model_prop_first = null;
            T_BAS_DistributionProp model_prop_second = null;
            T_BAS_DistributionProp model_prop_third = null;
            Guid? memberGuid = null;
            foreach (var merchant in list_merchant)
            {
                //分销佣金
                using (var tran = new SqlRTransaction())
                {
                    try
                    {
                        #region sql
                        var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                        var querywechat = Factory.CreateT_WX_WeChat(tran);
                        var query_order = Factory.CreateT_BAS_Orders(tran);
                        var query_parameter = Factory.CreateT_SYS_Parameter(tran);
                        var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                        var query_distributionProp = Factory.CreateT_BAS_DistributionProp(tran);
                        var query_distributionCommissions = Factory.CreateT_BAS_DistributionCommissions(tran);
                        var query_distribute = Factory.CreateT_BAS_Distribute(tran);
                        var query_merchant = Factory.CreateT_BAS_Merchants(tran);
                        var query_member = Factory.CreateT_BAS_Member(tran);
                        var query_withdrawsCommission = Factory.CreateT_BAS_WithdrawsCommission(tran);
                        var query_product = Factory.CreateProcedure(tran);
                        //var query_distributeOrder = Factory.CreateT_ST_DistributeOrder(tran);
                        var query_InTrade = Factory.CreateT_INT_IntegralTrading(tran);
                        #endregion
                        tran.BeginTransaction();
                        #region
                        if (merchant.WeChatGuid == null) continue;

                        var weChat = querywechat.GetDataByGuid(merchant.WeChatGuid.Value, false);

                        if (weChat == null) continue;

                        //var wechant = querywechat.GetFirstData(a => a.WeChatGuid == merchant.WeChatGuid,false,null,OrderMethods.Default,LockType.Default,false);
                        List<T_BAS_Orders> list_order = query_order.GetList(a => a.IsDistribute == true && a.OrderState == DictionaryConst.OrderState.Completed && a.MerchantGuid == merchant.MerchantGuid, false, null, OrderMethods.Default, LockType.Default, false);
                        if (list_order.Count == 0)
                        {
                            messageBox.Add(new MessageBox(false, "没有满足条件的分销订单需结算"));
                            continue;
                        }
                        #region 1、验证参数
                        T_SYS_Parameter model_parameter = query_parameter.GetFirstData(a => a.ParameterName == ParameterName.CommissionMember.CommissionSettlementTime && a.MerchantGuid == merchant.MerchantGuid, false, null, OrderMethods.Default, LockType.Default, false);
                        if (model_parameter == null)
                        {
                            //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "未设置佣金结算时间"));
                            continue;
                        }
                        //T_SYS_Parameter model_parameter_firstCommission = query_parameter.GetFirstData(a => a.ParameterName == ParameterName.CommissionMember.FirstCommission && a.MerchantGuid == merchant.MerchantGuid, false, null, OrderMethods.Default, LockType.Default, false);
                        //if (model_parameter_firstCommission == null)
                        //{
                        //    //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "未设置一级佣金结算比例"));
                        //    continue;
                        //}
                        //T_SYS_Parameter model_parameter_secondCommission = query_parameter.GetFirstData(a => a.ParameterName == ParameterName.CommissionMember.SecondCommission && a.MerchantGuid == merchant.MerchantGuid, false, null, OrderMethods.Default, LockType.Default, false);
                        //if (model_parameter_secondCommission == null)
                        //{
                        //    //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "未设置二级佣金结算比例"));
                        //    continue;
                        //}
                        //T_SYS_Parameter model_parameter_thirdCommission = query_parameter.GetFirstData(a => a.ParameterName == ParameterName.CommissionMember.ThirdCommission && a.MerchantGuid == merchant.MerchantGuid, false, null, OrderMethods.Default, LockType.Default, false);
                        //if (model_parameter_thirdCommission == null)
                        //{
                        //    //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "未设置三级佣金结算比例"));
                        //    continue;

                        //}
                        #endregion


                        //var template = querytemp.GetFirstData(a => a.MerchantGuid == merchant.MerchantGuid && a.TemplateNo == DictionaryConst.TemplateMessage.佣金提醒, false, null, OrderMethods.Default, LockType.Default, false);

                        try
                        {
                            //2.	结算逻辑：
                            //a)	符合条件的分销订单：订单完成时间+参数030204>当前时间 
                            foreach (T_BAS_Orders item in list_order)
                            {
                                #region 2、验证分销订单是否符合结算条件
                                if (item.CompletedTime == null)
                                {
                                    continue;
                                }
                                if ((DateTimeEx.DateDiff(item.CompletedTime.Value) < int.Parse(model_parameter.ParameterValue) && int.Parse(model_parameter.ParameterValue) != 0))
                                {
                                    //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "该订单不满足佣金结算时间限制"));
                                    continue;
                                }

                                var model_distribute = query_distribute.GetFirstData(a => a.OrderGuid == item.OrderGuid && a.MerchantGuid == item.MerchantGuid, false, null, OrderMethods.Default, LockType.Default, false);
                                //是否有分销订单
                                if (model_distribute == null)
                                {
                                    //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "找不到与该订单相关联的分销订单"));
                                    continue;
                                }
                                if (item.CompletedTime == null)
                                {
                                    //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "该订单尚未完成"));
                                    continue;
                                }

                                //分销订单是否已结算
                                if (model_distribute.IsSettlement == true)
                                {
                                    //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "该订单已结算"));
                                    continue;
                                }

                                #endregion

                                #region 3、验证订单明细是否符合结算条件
                                List<T_BAS_OrderDetails> list_orderDetail = query_orderDetail.GetList(a => a.OrderGuid == item.OrderGuid && a.State == DictionaryConst.OrderDetailState.Null, false, null, OrderMethods.Default, LockType.Default, false);
                                if (list_orderDetail.Count == 0)
                                {
                                    //messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, "找不到与该订单相关联的订单明细"));
                                    continue;

                                }
                                #endregion

                                #region 补充 分销赠送积分处理 Bing 151225

                                if (item.PresentExp > 0)
                                {
                                    //当前订单下正常&完成所有明细总额
                                    var detailSum = list_orderDetail.Sum(c => c.Amount);
                                    //对应规则
                                    var ruleEntity = new T_INT_IntegralRules()
                                    {
                                        IntegralEnable = true,
                                        ProductAmount = item.InProductAmount,
                                        PresentExp = item.InPresentExp
                                    };
                                    //赠送积分
                                    var tempIntegral = 0;
                                    IntegralRulesManage.GetIntegral(detailSum, ruleEntity, out tempIntegral);

                                    //赠送
                                    if (tempIntegral > 0)
                                    {
                                        var member = query_member.GetFirstData(c => c.MemberGuid == item.MemberGuid && c.MerchantGuid == item.MerchantGuid, isFilterMerchant: false);
                                        var newIntegral = (member.Integral ?? 0) + tempIntegral;
                                        query_member.Update(c => new object[]
                                    {
                                        c.Integral==newIntegral
                                    }, c => c.MemberGuid == member.MemberGuid && c.MerchantGuid == item.MerchantGuid, isFilterMerchant: false);

                                        query_InTrade.Add(new T_INT_IntegralTrading()
                                        {
                                            IntegralTradingGuid = Guid.NewGuid(),
                                            MemberGuid = member.MemberGuid,
                                            MerchantGuid = member.MerchantGuid,
                                            TradeIntegral = tempIntegral,
                                            IntegralBalance = newIntegral,
                                            OrderGuid = item.OrderGuid,
                                            TradeType = IntegralTradingConst.TradeType.PresentExpType,
                                            TradeDate = DateTime.Now,
                                            IntegralTo = IntegralTradingConst.IntegralToDir.Income
                                        });
                                    }
                                }

                                #endregion

                                #region 运费返佣 zhou 2016/4/8
                                decimal firstCommission = 0, secondCommission = 0, thridCommission = 0;
                                if (item.ProductClassify == 3)//零元购只有一个商品
                                {
                                    firstCommission = item.FreightFirstCom.Value;
                                    secondCommission = item.FreightSecondCom.Value;
                                    thridCommission = item.FreightThirdCom.Value;
                                }
                                #endregion

                                #region 4、插入佣金结算记录表并更新分销会员属性表
                                switch (model_distribute.DistributionLevel)
                                {
                                    #region 插入佣金结算记录表
                                    case DictionaryConst.DistributionLevel.FirstLevel:
                                        #region 一级佣金
                                        //b)	生成订单所属分销商的佣金结算记录（一级佣金），每个订单明细商品生成一条佣金结算记录
                                        try
                                        {
                                            var freightCom = item.Freight.Value * firstCommission;
                                            //一级佣金
                                            foreach (T_BAS_OrderDetails model in list_orderDetail)
                                            {
                                                T_BAS_DistributionCommissions entity = new T_BAS_DistributionCommissions()
                                                {
                                                    DistributionCommissionGuid = Guid.NewGuid(),
                                                    CommissionAmount = model.FirstCommission + freightCom,
                                                    StockDate = DateTime.Now,
                                                    MemberGuid = GetMember(model_distribute.DistributionPropGuid.Value),//获取会员Guid
                                                    OrderDetailGuid = model.OrderDetailGuid,
                                                    DistributeGuid = model_distribute.DistributeGuid,
                                                    DistributionPropGuid = model_distribute.DistributionPropGuid,
                                                    Level = model_distribute.DistributionLevel,
                                                    MerchantGuid = item.MerchantGuid.Value
                                                };
                                                query_distributionCommissions.Add(entity);
                                            }
                                            //更新分销会员属性表
                                            model_prop_first = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.DistributionPropGuid, false, null, OrderMethods.Default, LockType.Default, false);
                                            if (model_prop_first != null)
                                            {
                                                if (model_prop_first.DistributionCommissions == null)
                                                {
                                                    model_prop_first.DistributionCommissions = 0;
                                                }
                                                if (model_prop_first.DistributionAmount == null)
                                                {
                                                    model_prop_first.DistributionCommissions = 0;
                                                }
                                                model_prop_first.DistributionCommissions += model_distribute.FirstCommission + freightCom;//分销佣金
                                                model_prop_first.DistributionAmount += item.WXPayMoney ?? item.TotalMoney;//分销金额
                                                query_distributionProp.Update(model_prop_first, false);
                                            }
                                            #region  模板消息

                                            //if (template != null && weChat != null && model_distribute.FirstCommission != null && model_distribute.FirstCommission.Value > 0)
                                            //{
                                            //    memberGuid = GetMember(model_distribute.DistributionPropGuid.Value);
                                            //    string OpenID = memberGuid == null ? "" : MemberManage.GetMemberByGuid(memberGuid.Value).MemberOpenID;
                                            //    MessageTemplateManage.SendMessage_Commission(merchant.UserID, template.TemplateID, OpenID, item.OrderNo, model_distribute.FirstCommission.Value, weChat.appid);
                                            //}
                                            #endregion
                                        }
                                        catch (Exception err)
                                        {
                                            messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, err.Message));
                                            continue;
                                        }
                                        #endregion
                                        break;
                                    case DictionaryConst.DistributionLevel.SecondLevel:
                                        #region 二级佣金
                                        //c)	如果该分销商存在上级分销商，则生成上级分销商的佣金结算记录（二级佣金），每个订单明细商品生成二条佣金结算记录。
                                        try
                                        {
                                            var freightCom1 = item.Freight.Value * firstCommission;
                                            var freightCom2 = item.Freight.Value * secondCommission;
                                            foreach (T_BAS_OrderDetails model in list_orderDetail)
                                            {
                                                //一级佣金
                                                T_BAS_DistributionCommissions entity_first = new T_BAS_DistributionCommissions()
                                                {
                                                    DistributionCommissionGuid = Guid.NewGuid(),
                                                    CommissionAmount = model.FirstCommission + freightCom1,
                                                    StockDate = DateTime.Now,
                                                    MemberGuid = GetMember(model_distribute.DistributionPropGuid.Value),//获取会员Guid
                                                    OrderDetailGuid = model.OrderDetailGuid,
                                                    DistributeGuid = model.DistributeGuid,
                                                    DistributionPropGuid = model_distribute.DistributionPropGuid,
                                                    Level = DictionaryConst.DistributionLevel.FirstLevel,
                                                    MerchantGuid = item.MerchantGuid.Value
                                                };
                                                //二级佣金
                                                T_BAS_DistributionCommissions entity_second = new T_BAS_DistributionCommissions()
                                                {
                                                    DistributionCommissionGuid = Guid.NewGuid(),
                                                    CommissionAmount = model.SecondCommission + freightCom2,
                                                    StockDate = DateTime.Now,
                                                    MemberGuid = GetMember(model_distribute.SuperiorDistributorGuid.Value),
                                                    OrderDetailGuid = model.OrderDetailGuid,
                                                    DistributeGuid = model.DistributeGuid,
                                                    DistributionPropGuid = model_distribute.SuperiorDistributorGuid,
                                                    Level = DictionaryConst.DistributionLevel.SecondLevel,
                                                    MerchantGuid = item.MerchantGuid.Value
                                                };
                                                //合计分销佣金
                                                query_distributionCommissions.Add(entity_first);
                                                query_distributionCommissions.Add(entity_second);
                                            }
                                            //更新分销会员属性表
                                            //一级
                                            model_prop_first = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.DistributionPropGuid, false, null, OrderMethods.Default, LockType.Default, false);
                                            model_prop_second = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.SuperiorDistributorGuid, false, null, OrderMethods.Default, LockType.Default, false);
                                            if (model_prop_first != null)
                                            {
                                                if (model_prop_first.DistributionCommissions == null)
                                                {
                                                    model_prop_first.DistributionCommissions = 0;
                                                }
                                                if (model_prop_first.DistributionAmount == null)
                                                {
                                                    model_prop_first.DistributionCommissions = 0;
                                                }
                                                model_prop_first.DistributionCommissions += model_distribute.FirstCommission + freightCom1;//分销佣金
                                                model_prop_first.DistributionAmount += item.WXPayMoney ?? item.TotalMoney;//分销金额
                                                query_distributionProp.Update(model_prop_first, false);
                                            }
                                            //二级
                                            if (model_prop_second != null)
                                            {
                                                if (model_prop_second.DistributionCommissions == null)
                                                {
                                                    model_prop_second.DistributionCommissions = 0;
                                                }
                                                if (model_prop_second.DistributionAmount == null)
                                                {
                                                    model_prop_second.DistributionCommissions = 0;
                                                }
                                                model_prop_second.DistributionCommissions += model_distribute.SecondCommission + freightCom2;//分销佣金
                                                model_prop_second.DistributionAmount += item.WXPayMoney ?? item.TotalMoney;//分销金额
                                                query_distributionProp.Update(model_prop_second, false);
                                            }
                                            #region  模板消息
                                            //if (template != null && weChat != null)
                                            //{
                                            //    if (model_distribute.DistributionPropGuid != null && model_distribute.FirstCommission != null && model_distribute.FirstCommission.Value > 0)
                                            //    {
                                            //        memberGuid = GetMember(model_distribute.DistributionPropGuid.Value);
                                            //        string OpenID = memberGuid == null ? "" : MemberManage.GetMemberByGuid(memberGuid.Value).MemberOpenID;
                                            //        MessageTemplateManage.SendMessage_Commission(merchant.UserID, template.TemplateID, OpenID, item.OrderNo, model_distribute.FirstCommission.Value, weChat.appid);
                                            //    }
                                            //    if (model_distribute.SuperiorDistributorGuid != null && model_distribute.SecondCommission != null && model_distribute.SecondCommission.Value > 0)
                                            //    {
                                            //        memberGuid = GetMember(model_distribute.SuperiorDistributorGuid.Value);
                                            //        string OpenID = memberGuid == null ? "" : MemberManage.GetMemberByGuid(memberGuid.Value).MemberOpenID;
                                            //        MessageTemplateManage.SendMessage_Commission(merchant.UserID, template.TemplateID, OpenID, item.OrderNo, model_distribute.SecondCommission.Value, weChat.appid);
                                            //    }
                                            //}
                                            #endregion
                                        }
                                        catch (Exception err)
                                        {
                                            messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, err.Message));
                                            continue;
                                        }
                                        #endregion
                                        break;
                                    case DictionaryConst.DistributionLevel.ThirdLevel:
                                        #region 三级佣金
                                        //d)	如果该分销商存在上上级分销商，则生成上上级分销商的佣金结算记录（三级佣金），每个订单明细商品生成三条佣金结算记录。
                                        try
                                        {
                                            var freightCom1 = item.Freight.Value * firstCommission;
                                            var freightCom2 = item.Freight.Value * secondCommission;
                                            var freightCom3 = item.Freight.Value * thridCommission;
                                            foreach (T_BAS_OrderDetails model in list_orderDetail)
                                            {
                                                //一级佣金
                                                T_BAS_DistributionCommissions entity_one = new T_BAS_DistributionCommissions()
                                                {
                                                    DistributionCommissionGuid = Guid.NewGuid(),
                                                    CommissionAmount = model.FirstCommission + freightCom1,
                                                    StockDate = DateTime.Now,
                                                    MemberGuid = GetMember(model_distribute.DistributionPropGuid.Value),//获取会员Guid
                                                    OrderDetailGuid = model.OrderDetailGuid,
                                                    DistributeGuid = model.DistributeGuid,
                                                    DistributionPropGuid = model_distribute.DistributionPropGuid,
                                                    Level = DictionaryConst.DistributionLevel.FirstLevel,
                                                    MerchantGuid = item.MerchantGuid.Value
                                                };
                                                //二级佣金
                                                T_BAS_DistributionCommissions entity_two = new T_BAS_DistributionCommissions()
                                                {
                                                    DistributionCommissionGuid = Guid.NewGuid(),
                                                    CommissionAmount = model.SecondCommission + freightCom2,
                                                    StockDate = DateTime.Now,
                                                    MemberGuid = GetMember(model_distribute.SuperiorDistributorGuid.Value),
                                                    OrderDetailGuid = model.OrderDetailGuid,
                                                    DistributeGuid = model.DistributeGuid,
                                                    DistributionPropGuid = model_distribute.SuperiorDistributorGuid,
                                                    Level = DictionaryConst.DistributionLevel.SecondLevel,
                                                    MerchantGuid = item.MerchantGuid.Value
                                                };
                                                //三级佣金
                                                T_BAS_DistributionCommissions entity_three = new T_BAS_DistributionCommissions()
                                                {
                                                    DistributionCommissionGuid = Guid.NewGuid(),
                                                    CommissionAmount = model.ThirdCommission + freightCom3,
                                                    StockDate = DateTime.Now,
                                                    MemberGuid = GetMember(model_distribute.TopDistributorGuid.Value),
                                                    OrderDetailGuid = model.OrderDetailGuid,
                                                    DistributeGuid = model.DistributeGuid,
                                                    DistributionPropGuid = model_distribute.TopDistributorGuid,
                                                    Level = DictionaryConst.DistributionLevel.ThirdLevel,
                                                    MerchantGuid = item.MerchantGuid.Value
                                                };
                                                query_distributionCommissions.Add(entity_one);
                                                query_distributionCommissions.Add(entity_two);
                                                query_distributionCommissions.Add(entity_three);
                                            }
                                            //更新分销会员属性表
                                            model_prop_first = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.DistributionPropGuid.Value, false, null, OrderMethods.Default, LockType.Default, false);
                                            model_prop_second = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.SuperiorDistributorGuid.Value, false, null, OrderMethods.Default, LockType.Default, false);
                                            model_prop_third = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == model_distribute.TopDistributorGuid.Value, false, null, OrderMethods.Default, LockType.Default, false);
                                            if (model_prop_first != null)
                                            {
                                                if (model_prop_first.DistributionCommissions == null)
                                                {
                                                    model_prop_first.DistributionCommissions = 0;
                                                }
                                                if (model_prop_first.DistributionAmount == null)
                                                {
                                                    model_prop_first.DistributionCommissions = 0;
                                                }
                                                model_prop_first.DistributionCommissions += model_distribute.FirstCommission + freightCom1;//分销佣金
                                                model_prop_first.DistributionAmount += item.WXPayMoney ?? item.TotalMoney;//分销金额
                                                query_distributionProp.Update(model_prop_first, false);
                                            }
                                            //二级
                                            if (model_prop_second != null)
                                            {
                                                if (model_prop_second.DistributionCommissions == null)
                                                {
                                                    model_prop_second.DistributionCommissions = 0;
                                                }
                                                if (model_prop_second.DistributionAmount == null)
                                                {
                                                    model_prop_second.DistributionCommissions = 0;
                                                }
                                                model_prop_second.DistributionCommissions += model_distribute.SecondCommission + freightCom2;//分销佣金
                                                model_prop_second.DistributionAmount += item.WXPayMoney ?? item.TotalMoney;//分销金额
                                                query_distributionProp.Update(model_prop_second, false);
                                            }
                                            //三级
                                            if (model_prop_third != null)
                                            {
                                                if (model_prop_third.DistributionCommissions == null)
                                                {
                                                    model_prop_third.DistributionCommissions = 0;
                                                }
                                                if (model_prop_third.DistributionAmount == null)
                                                {
                                                    model_prop_third.DistributionCommissions = 0;
                                                }
                                                model_prop_third.DistributionCommissions += model_distribute.ThirdCommission + freightCom3;//分销佣金
                                                model_prop_third.DistributionAmount += item.WXPayMoney ?? item.TotalMoney;//分销金额
                                                query_distributionProp.Update(model_prop_third, false);
                                            }
                                            #region  模板消息
                                            //if (template != null && weChat != null)
                                            //{

                                            //    if (model_distribute.DistributionPropGuid != null && model_distribute.FirstCommission != null && model_distribute.FirstCommission.Value > 0)
                                            //    {
                                            //        memberGuid = GetMember(model_distribute.DistributionPropGuid.Value);
                                            //        string OpenID = memberGuid == null ? "" : MemberManage.GetMemberByGuid(memberGuid.Value).MemberOpenID;
                                            //        MessageTemplateManage.SendMessage_Commission(merchant.UserID, template.TemplateID, OpenID, item.OrderNo, model_distribute.FirstCommission.Value, weChat.appid);
                                            //    }
                                            //    if (model_distribute.SuperiorDistributorGuid != null && model_distribute.SecondCommission != null && model_distribute.SecondCommission.Value > 0)
                                            //    {
                                            //        memberGuid = GetMember(model_distribute.SuperiorDistributorGuid.Value);
                                            //        string OpenID = memberGuid == null ? "" : MemberManage.GetMemberByGuid(memberGuid.Value).MemberOpenID;
                                            //        MessageTemplateManage.SendMessage_Commission(merchant.UserID, template.TemplateID, OpenID, item.OrderNo, model_distribute.SecondCommission.Value, weChat.appid);
                                            //    }
                                            //    if (model_distribute.TopDistributorGuid != null && model_distribute.ThirdCommission != null && model_distribute.ThirdCommission.Value > 0)
                                            //    {
                                            //        memberGuid = GetMember(model_distribute.TopDistributorGuid.Value);
                                            //        string OpenID = memberGuid == null ? "" : MemberManage.GetMemberByGuid(memberGuid.Value).MemberOpenID;
                                            //        MessageTemplateManage.SendMessage_Commission(merchant.UserID, template.TemplateID, OpenID, item.OrderNo, model_distribute.ThirdCommission.Value, weChat.appid);
                                            //    }
                                            //}
                                            #endregion

                                        }
                                        catch (Exception err)
                                        {
                                            messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, err.Message));
                                            continue;
                                        }
                                        #endregion
                                        break;
                                    #endregion
                                }
                                #endregion

                                #region 5、更新分销订单属性表
                                //更新分销订单属性表
                                try
                                {
                                    model_distribute.IsSettlement = true;
                                    model_distribute.SettlementDate = DateTime.Now;
                                    query_distribute.Update(model_distribute, false);
                                }
                                catch (Exception err)
                                {
                                    messageBox.Add(new MessageBox(false, merchant.StoreTitle, item.OrderNo, err.Message));
                                    continue;
                                }
                                #endregion
                            }
                            #region 6、更新商家表
                            //更新商家表
                            try
                            {
                                List<T_BAS_WithdrawsCommission> list_withdrawsCommission = query_withdrawsCommission.GetList(a => a.MerchantGuid == merchant.MerchantGuid.ToString() && a.State == DictionaryConst.WithdriwalCom.WithdrawalsSuccess, false, null, OrderMethods.Default, LockType.Default, false);
                                if (merchant != null)
                                {
                                    if (merchant.TotalDistributionOrders == null)
                                    {
                                        merchant.TotalDistributionOrders = 0;
                                    }
                                    if (merchant.DistributionOrdersAmount == null)
                                    {
                                        merchant.DistributionOrdersAmount = 0;
                                    }
                                    if (merchant.TotalDistributor == null)
                                    {
                                        merchant.TotalDistributor = 0;
                                    }
                                    if (merchant.CumulativeDistributionAmount == null)
                                    {
                                        merchant.CumulativeDistributionAmount = 0;
                                    }
                                    //var list_distributeOrder = query_distributeOrder.GetList(a => a.MerchantGuid == merchant.MerchantGuid, false, null, OrderMethods.Default, LockType.Default, false);
                                    ///处理运费返佣 zhou 2016/4/6 
                                    var list_distributeOrder = Factory.CreateProcedure(tran).Get_Distribution_Order(merchant.MerchantGuid);
                                    if (list_distributeOrder.Count > 0)
                                    {
                                        merchant.TotalDistributionOrders = list_distributeOrder.Count();
                                        merchant.DistributionOrdersAmount = list_distributeOrder.Sum(a => a.TotalMoney);
                                        merchant.TotalDistributor = query_distributionProp.GetCount(a => a.IsEnable == true);

                                        merchant.CumulativeDistributionAmount = list_distributeOrder.Sum(a => a.TotalCommission);
                                    }
                                    if (list_withdrawsCommission.Count > 0)
                                    {
                                        var applymount = list_withdrawsCommission.Sum(a => a.ApplyAmount);
                                        merchant.MentionedAmount = applymount == null ? 0 : applymount.Value;
                                    }
                                    else
                                    {
                                        merchant.MentionedAmount = 0;
                                    }
                                    query_merchant.Update(merchant, false);

                                }

                            }
                            catch (Exception err)
                            {
                                messageBox.Add(new MessageBox(false, merchant.StoreTitle, err.Message));
                                continue;
                            }
                            #endregion

                            tran.Commit();
                        }
                        catch (Exception err)
                        {
                            messageBox.Add(new MessageBox(false, err.Message));
                            continue;
                        }
                        #endregion
                    }
                    catch (Exception err)
                    {
                        tran.Rollback();
                        continue;
                    }
                }
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            foreach (var m in messageBox)
            {
                sb.AppendFormat("[Merchants:{0},OrderNo:{1},State:{2},ClearDate:{3},Msg:{4}],\r\n", m.Merchants, m.OrderNo, m.State, m.ClearDate, m.Msg);
            }
            sb.Append("}");

            return new Result(true) { Msg = sb.ToString() };
        }
        #endregion


        #region 总部订单积分赠送处理
        //定时任务 2016/03/18 zhou
        public static void ExtHqOrderPresentExp()
        {
            using (SqlRTransaction tran = new SqlRTransaction())
            {
                var query_member = Factory.CreateT_BAS_Member(tran);
                var query_InTrade = Factory.CreateT_INT_IntegralTrading(tran);
                var query_order = Factory.CreateT_BAS_Orders(tran);
                try
                {
                    ExtHqOrderPresentExp(tran, null, query_member, query_InTrade, query_order);
                }
                catch { }
            }
        }

        /// <summary>
        /// 总部订单积分赠送处理
        /// </summary>
        /// <returns></returns>
        public static void ExtHqOrderPresentExp(SqlRTransaction tran, Guid? merchantGuid, IQuery<T_BAS_Member> query_member, IQuery<T_INT_IntegralTrading> query_InTrade, IQuery<T_BAS_Orders> query_order)
        {
            var query = Factory.CreateT_BAS_OrderDetailsWithHq(tran);

            //获取总部明细订单-已完成,未赠送。
            var list = query.GetList(a => a.OrderState == DictionaryConst.OrderState.Completed && a.State == DictionaryConst.OrderDetailState.Null && a.PresentExpOr > 0 && (a.HasPresented == false || a.HasPresented.SqlIsNull()) && a.MerchantGuid == merchantGuid, true, null, OrderMethods.Default, LockType.Default, false);
            if (list != null && list.Count > 0)
            {
                list.GroupBy(o => o.OrderGuid).ToList().ForEach(d =>
                {
                    //当前订单下正常&完成所有明细总额
                    var detailSum = d.Sum(c => c.Amount);
                    var currOr = d.First();
                    //对应规则
                    var ruleEntity = new T_INT_IntegralRules()
                    {
                        IntegralEnable = true,
                        ProductAmount = currOr.InProductAmount,
                        PresentExp = currOr.InPresentExp
                    };
                    //赠送积分
                    var tempIntegral = 0;
                    IntegralRulesManage.GetIntegral(detailSum, ruleEntity, out tempIntegral);

                    //赠送
                    if (tempIntegral > 0)
                    {
                        var newIntegral = (currOr.Integral ?? 0) + tempIntegral;
                        query_member.Update(c => new object[]
                                    {
                                        c.Integral==newIntegral
                                    }, c => c.MemberGuid == currOr.MemberGuid && c.MerchantGuid == currOr.MerchantGuid, isFilterMerchant: false);

                        query_InTrade.Add(new T_INT_IntegralTrading()
                        {
                            IntegralTradingGuid = Guid.NewGuid(),
                            MemberGuid = currOr.MemberGuid,
                            MerchantGuid = currOr.MerchantGuid,
                            TradeIntegral = tempIntegral,
                            IntegralBalance = newIntegral,
                            OrderGuid = currOr.OrderGuid.Value,
                            TradeType = IntegralTradingConst.TradeType.PresentExpType,
                            TradeDate = DateTime.Now,
                            IntegralTo = IntegralTradingConst.IntegralToDir.Income
                        });

                        //修改订单积分已赠送标记
                        query_order.Update(c => new object[] { 
                            c.HasPresented==true,
                            c.PresentedTime==DateTime.Now
                        }, c => c.OrderGuid == currOr.OrderGuid && c.MerchantGuid == currOr.MerchantGuid, isFilterMerchant: false);

                    }

                });
            }

        }
        #endregion

        #region 订单预存流水计算
        /// <summary>
        /// 订单预存流水计算
        /// </summary>
        public static void CountAgentFactorage()
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_OrderDetailsWithDiscout(tran);
                var queryAccout = Factory.CreateT_BAS_AdvanceAgentAccount(tran);
                var queryOrder = Factory.CreateT_BAS_Orders(tran);
                var queryFlagshipOrders = Factory.CreateT_BAS_FlagshipOrders(tran);
                var queryMer = Factory.CreateT_BAS_Merchants(tran);
                var querySys = Factory.CreateT_SYS_Parameter(tran);

                var list = query.GetList(a => a.OrderState == DictionaryConst.OrderState.Completed && a.State == DictionaryConst.OrderDetailState.Null && (a.HasFactoraged == false || a.HasFactoraged.SqlIsNull()) && a.FatherMerchantGuid.SqlIsNotNull() && a.PaymentType == AgentProductDiscountConst.PaymentType.预存 && a.BeNn == 0, false, c => c.OrderTime, OrderMethods.ASC, LockType.Default, false);
                if (list != null && list.Count > 0)
                {
                    var listSys = querySys.GetList(c => c.MerchantGuid.SqlIn(list.Select(o => o.MerchantGuid.ToString()).Distinct().ToArray()) && c.ParameterName == ParameterName.Refund.RefundService_validity, isFilterMerchant: false);

                    var merOrderList = list.GroupBy(c => c.MerchantGuid).ToList();
                    //var merAccount = queryAccout.GetList(c => c.MerchantGuid.SqlIn(merOrderList.Select(m => m.Key).ToArray()), false, c => c.TradingDate, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                    var merList = queryMer.GetList(c => c.MerchantGuid.SqlIn(merOrderList.Select(m => m.Key.Value).ToArray()), isFilterMerchant: false);
                    var accoutList = new List<T_BAS_AdvanceAgentAccount>();
                    //遍历商家
                    merOrderList.ForEach(g =>
                    {
                        var data = DateTime.Now;
                        var tic = 1;
                        var currMer = merList.First(c => c.MerchantGuid == g.Key);
                        var currPre = (currMer.Prestore ?? 0M);
                        //遍历所有订单
                        g.ToList().ForEach(d =>
                        {
                            if (listSys != null && listSys.Count > 0)
                            {
                                var currPar = listSys.FirstOrDefault(c => c.MerchantGuid == d.MerchantGuid);
                                if (currPar != null && (!string.IsNullOrEmpty(currPar.ParameterValue)))
                                {
                                    var fixDay = int.Parse(currPar.ParameterValue);
                                    if (DateTimeEx.DateDiff(d.CompletedTime.Value) < fixDay)
                                    {
                                        return;
                                    }
                                }
                            }
                            //计算最新可用预存
                            currPre -= decimal.Round((d.AgentPrice * d.AgentDiscount).Value / 100, 2, MidpointRounding.AwayFromZero) * d.Quantity.Value;
                            //更新集合更新，不冲突
                            currMer.Prestore = currPre;
                            currMer.EntityState = EntityStates.ToBeUpdated;
                            //增加预存流水
                            var entity = new T_BAS_AdvanceAgentAccount()
                            {
                                AdvanceAgentAccountGuid = Guid.NewGuid(),
                                MerchantGuid = d.MerchantGuid,
                                SMerchantGuid = d.MerchantGuid,
                                FlagshipOrdersGuid = d.FlagshipOrdersGuid,
                                TradingCode = d.OrderNo,
                                TradingType = AdvanceAgentAccountConst.TradingType.订单结算,
                                TradingMain = d.ProductName,
                                AvailableBalance = currPre,
                                TradingAmount = -decimal.Round((d.AgentPrice * d.AgentDiscount).Value / 100, 2, MidpointRounding.AwayFromZero) * d.Quantity,
                                AgentPrice = d.AgentPrice,
                                Discount = d.AgentDiscount,
                                AgentDiscountPrice = decimal.Round((d.AgentPrice * d.AgentDiscount).Value / 100, 2, MidpointRounding.AwayFromZero),
                                Remark = "用户下单完成",
                                TradingDate = data.AddSeconds(tic++),
                                EntityState = EntityStates.ToBeAdd
                            };
                            accoutList.Add(entity);

                        });
                    });

                    try
                    {
                        tran.BeginTransaction();
                        if (accoutList != null && accoutList.Count > 0)
                        {
                            var fsOrders = queryFlagshipOrders.GetList(c => c.FlagshipOrdersGuid.SqlIn(accoutList.Select(a => a.FlagshipOrdersGuid.Value).ToArray()), isFilterMerchant: false);

                            queryOrder.Update(c => new object[]{
                                c.HasFactoraged==true
                            }, c => c.OrderGuid.SqlIn(fsOrders.Select(p => p.OrderGuid.Value).Distinct().ToArray()), isFilterMerchant: false);

                            queryAccout.AddList(accoutList);
                            queryMer.UpdateList(merList);
                        }

                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        Wechat.LogManage.Log("订单预存流水统计出错：" + ex.Message);

                    }
                }
            }
        }
        #endregion

        #region 订单利润流水计算-总部版
        /// <summary>
        /// 订单利润流水计算-总部版 　
        /// </summary>
        public static void CountAgentProfit()
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_OrderDetailsWithDiscout(tran);
                var queryProfit = Factory.CreateT_BAS_TradingProfit(tran);
                var queryOrder = Factory.CreateT_BAS_Orders(tran);
                var query_FactorageAccount = Factory.CreateT_BAS_FactorageAccount(tran);
                var query_mer = Factory.CreateT_BAS_Merchants(tran);
                var querySys = Factory.CreateT_SYS_Parameter(tran);
                var list = query.GetList(a => a.OrderState == DictionaryConst.OrderState.Completed && a.State == DictionaryConst.OrderDetailState.Null && (a.HasProfited == false || a.HasProfited.SqlIsNull()) && a.FatherMerchantGuid.SqlIsNotNull() && a.UserWeChatType == AgentRuleConst.UserWeChatType.总部 && a.BeNn == 0, false, c => c.OrderTime, OrderMethods.ASC, LockType.Default, false);
                if (list != null && list.Count > 0)
                {
                    var listSys = querySys.GetList(c => c.MerchantGuid.SqlIn(list.Select(o => o.MerchantGuid.ToString()).Distinct().ToArray()) && c.ParameterName == ParameterName.Refund.RefundService_validity, isFilterMerchant: false);

                    List<T_BAS_TradingProfit> ProfitList = new List<T_BAS_TradingProfit>();
                    list.ForEach(d =>
                    {
                        if (listSys != null && listSys.Count > 0)
                        {
                            var currPar = listSys.FirstOrDefault(c => c.MerchantGuid == d.MerchantGuid);
                            if (currPar != null && (!string.IsNullOrEmpty(currPar.ParameterValue)))
                            {
                                var fixDay = int.Parse(currPar.ParameterValue);
                                if (DateTimeEx.DateDiff(d.CompletedTime.Value) < fixDay)
                                {
                                    return;
                                }
                            }
                        }

                        var tempProfit = d.WXPayMoney - decimal.Round((d.AgentPrice * d.AgentDiscount / 100).Value, 2, MidpointRounding.AwayFromZero) * d.Quantity - (d.TotalCommission ?? 0);
                        var entity = new T_BAS_TradingProfit()
                        {
                            TradingProfitGuid = Guid.NewGuid(),
                            MerchantGuid = d.MerchantGuid,
                            SMerchantGuid = d.MerchantGuid,
                            OrderGuid = d.OrderGuid,
                            ProductName = d.ProductName,
                            AgentPrice = d.AgentPrice,
                            TransactionAmount = d.WXPayMoney,
                            Discount = d.AgentDiscount,
                            TradeDate = d.PayTime,
                            //PurchaseAmount  
                            //BackAgentAmount  
                            TotalCommission = d.TotalCommission,
                            Profit = tempProfit,
                            EntityState = EntityStates.ToBeAdd
                        };
                        ProfitList.Add(entity);
                    });
                    try
                    {
                        tran.BeginTransaction();
                        if (ProfitList != null && ProfitList.Count > 0)
                        {
                            queryOrder.Update(c => new object[]{
                                c.HasProfited==true
                            }, c => c.OrderGuid.SqlIn(ProfitList.Select(p => p.OrderGuid.Value).Distinct().ToArray()), isFilterMerchant: false);
                            queryProfit.AddList(ProfitList);

                            //补充账户流水 临时 暂定
                            var fcaList = new List<T_BAS_FactorageAccount>();
                            var merList = query_mer.GetList(m => m.MerchantGuid.SqlIn(ProfitList.Select(c => c.MerchantGuid.ToString()).Distinct().ToArray()), isFilterMerchant: false);

                            ProfitList.GroupBy(m => m.MerchantGuid).ToList().ForEach(o =>
                            {

                                var sumPr = o.Sum(c => c.Profit);
                                var merchant = o.First().MerchantGuid;
                                ////var available = 0m;
                                ////var freeze = 0m;
                                ////AgentCommissionManage.GetAvailableAndFreeze(merchant, ref available, ref freeze);
                                //var currBalance = available + (sumPr ?? 0);

                                var currMer = merList.First(m => m.MerchantGuid == merchant);
                                currMer.FsBalance = (currMer.FsBalance ?? 0M) + sumPr;
                                currMer.EntityState = EntityStates.ToBeUpdated;

                                var tempGuid = Guid.NewGuid();
                                var tradingDate = DateTime.Now;

                                fcaList.Add(new T_BAS_FactorageAccount()
                                {
                                    FactorageAccountGuid = tempGuid,
                                    MerchantGuid = merchant,
                                    SMerchantGuid = merchant,
                                    TradingMain = DateTime.Now.ToString(string.Format("yyyy{0}MM{1}dd{2}", "年", "月", "日") + "结算订单总利润"),
                                    TradingCode = DateTime.Now.ToString("yyyyMMddHHmmss") + string.Format("{0:D2}", AgentCommissionConst.TradingType.商品利润),
                                    AvailableBalance = currMer.FsBalance,
                                    TradingType = AgentCommissionConst.TradingType.商品利润,
                                    FactorageSubjectGuid = merchant,
                                    TradingAmount = sumPr,
                                    TradingDate = tradingDate,
                                    EntityState = EntityStates.ToBeAdd,
                                    Remark = "Profit"
                                });

                            });
                            query_mer.UpdateList(merList);
                            query_FactorageAccount.AddList(fcaList);
                        }
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        Wechat.LogManage.Log("订单利润流水统计_总部版 出错：" + ex.Message);

                    }
                }
            }

        }
        #endregion

        #region 订单利润流水计算-独立版
        /// <summary>
        /// 订单利润流水计算-独立版　
        /// </summary>
        public static void CountAgentProfit_Inden()
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_OrderDetailsWithDiscout(tran);
                var queryProfit = Factory.CreateT_BAS_TradingProfit(tran);
                var queryOrder = Factory.CreateT_BAS_Orders(tran);
                var query_FactorageAccount = Factory.CreateT_BAS_FactorageAccount(tran);
                var querySys = Factory.CreateT_SYS_Parameter(tran);
                var list = query.GetList(a => a.OrderState == DictionaryConst.OrderState.Completed && a.State == DictionaryConst.OrderDetailState.Null && (a.HasProfited == false || a.HasProfited.SqlIsNull()) && a.FatherMerchantGuid.SqlIsNotNull() && a.UserWeChatType == AgentRuleConst.UserWeChatType.代理商 && a.BeNn == 0, false, c => c.OrderTime, OrderMethods.ASC, LockType.Default, false);
                if (list != null && list.Count > 0)
                {
                    var listSys = querySys.GetList(c => c.MerchantGuid.SqlIn(list.Select(o => o.MerchantGuid.ToString()).Distinct().ToArray()) && c.ParameterName == ParameterName.Refund.RefundService_validity, isFilterMerchant: false);

                    List<T_BAS_TradingProfit> ProfitList = new List<T_BAS_TradingProfit>();
                    list.ForEach(d =>
                    {
                        if (listSys != null && listSys.Count > 0)
                        {
                            var currPar = listSys.FirstOrDefault(c => c.MerchantGuid == d.MerchantGuid);
                            if (currPar != null && (!string.IsNullOrEmpty(currPar.ParameterValue)))
                            {
                                var fixDay = int.Parse(currPar.ParameterValue);
                                if (DateTimeEx.DateDiff(d.CompletedTime.Value) < fixDay)
                                {
                                    return;
                                }
                            }
                        }

                        //--处理意外数据 Bing 160419
                        //if (d.WXPayMoney == null)
                        //{
                        //    return;
                        //}
                        Decimal? tempProfit = 0m;
                        try
                        {
                            tempProfit = d.WXPayMoney - decimal.Round((d.AgentPrice * d.AgentDiscount / 100).Value, 2, MidpointRounding.AwayFromZero) * d.Quantity - (d.TotalCommission ?? 0);
                        }
                        catch (Exception ex)
                        {
                            return;
                        }


                        var entity = new T_BAS_TradingProfit()
                        {
                            TradingProfitGuid = Guid.NewGuid(),
                            MerchantGuid = d.MerchantGuid,
                            SMerchantGuid = d.MerchantGuid,
                            OrderGuid = d.OrderGuid,
                            ProductName = d.ProductName,
                            AgentPrice = d.AgentPrice,
                            TransactionAmount = d.WXPayMoney,
                            Discount = d.AgentDiscount,
                            TradeDate = d.PayTime,
                            //PurchaseAmount  
                            //BackAgentAmount  
                            TotalCommission = d.TotalCommission,
                            Profit = tempProfit,
                            EntityState = EntityStates.ToBeAdd
                        };
                        ProfitList.Add(entity);
                    });
                    try
                    {
                        tran.BeginTransaction();
                        if (ProfitList != null && ProfitList.Count > 0)
                        {
                            queryOrder.Update(c => new object[]{
                                c.HasProfited==true
                            }, c => c.OrderGuid.SqlIn(ProfitList.Select(p => p.OrderGuid.Value).Distinct().ToArray()), isFilterMerchant: false);
                            queryProfit.AddList(ProfitList);

                        }
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        Wechat.LogManage.Log("订单利润流水统计_独立版 出错：" + ex.Message);

                    }
                }
            }

        }
        #endregion

        #region 代理商分红销售额计算（代理分红模式）
        /// <summary>
        /// 代理商分红销售额计算（代理分红模式）
        /// </summary>
        /// <returns></returns>
        public static void CountAgentSales()
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_OrderDetailsWithFlagship(tran);
                var query_Mer = Factory.CreateT_BAS_Merchants(tran);
                var query_Or = Factory.CreateT_BAS_Orders(tran);
                var querySys = Factory.CreateT_SYS_Parameter(tran);
                try
                {

                    var list = query.GetList(a => a.OrderState == DictionaryConst.OrderState.Completed && a.State == DictionaryConst.OrderDetailState.Null &&  /*(a.AgentComType == AgentRuleConst.AgentComType.垂直返佣 || a.AgentComType == AgentRuleConst.AgentComType.全线分红) &&/*待定范围*/ (a.HasCountSale == false || a.HasCountSale.SqlIsNull()) && a.FatherMerchantGuid.SqlIsNotNull() && a.BeNn == 0, true, c => c.OrderTime, OrderMethods.ASC, LockType.Default, false);

                    if (list != null && list.Count > 0)
                    {
                        var guids = list.Select(o => o.MerchantGuid.ToString()).Distinct().ToArray();
                        var listSys = querySys.GetList(c => c.MerchantGuid.SqlIn(guids) && c.ParameterName == ParameterName.Refund.RefundService_validity, isFilterMerchant: false);

                        var merList = query_Mer.GetList(c => c.MerchantGuid.SqlIn(guids), isFilterMerchant: false);
                        List<string> upOrders = new List<string>();
                        list.GroupBy(o => o.OrderGuid).ToList().ForEach(d =>
                        {
                            var currOr = d.First();

                            if (listSys != null && listSys.Count > 0)
                            {
                                var currPar = listSys.FirstOrDefault(c => c.MerchantGuid == currOr.MerchantGuid);
                                if (currPar != null && (!string.IsNullOrEmpty(currPar.ParameterValue)))
                                {
                                    var fixDay = int.Parse(currPar.ParameterValue);
                                    if (DateTimeEx.DateDiff(currOr.CompletedTime.Value) < fixDay)
                                    {
                                        return;
                                    }
                                }
                            }

                            upOrders.Add(d.Key.ToString());
                            var detailSum = d.Sum(c => c.WXPayMoney);
                            var currMer = merList.First(c => c.MerchantGuid == currOr.MerchantGuid);
                            currMer.TotalSales = (currMer.TotalSales ?? 0M) + detailSum;
                            currMer.EntityState = EntityStates.ToBeUpdated;
                        });

                        tran.BeginTransaction();

                        query_Or.Update(c => new object[]{
                          c.HasCountSale==true
                        }, c => c.OrderGuid.SqlIn(upOrders.Distinct().ToArray()), isFilterMerchant: false);
                        query_Mer.UpdateList(merList);

                        tran.Commit();
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    Wechat.LogManage.Log("代理商分红销售额计算（代理分红模式）出错：" + ex.Message);
                }
            }
        }
        #endregion

        #region 代理商商品佣金计算（代理分红模式） 待定
        /// <summary>
        ///  代理商商品佣金计算（代理分红模式） 待定
        /// </summary>
        /// <returns></returns>
        public static void CountAgentCommission()
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_OrderDetailsWithFlagship(tran);
                var query_FlagshipCommission = Factory.CreateT_BAS_FlagshipCommission(tran);
                var query_FactorageAccount = Factory.CreateT_BAS_FactorageAccount(tran);
                var query_fsOrder = Factory.CreateT_BAS_FlagshipOrders(tran);
                var query_mer = Factory.CreateT_BAS_Merchants(tran);
                var querySys = Factory.CreateT_SYS_Parameter(tran);
                try
                {

                    //获取明细订单列表-已完成，未计算分红
                    var list = query.GetList(a => a.OrderState == DictionaryConst.OrderState.Completed && a.State == DictionaryConst.OrderDetailState.Null && (a.AgentComType == AgentRuleConst.AgentComType.垂直返佣 || a.AgentComType == AgentRuleConst.AgentComType.全线分红) && (a.HasCountedCommission == false || a.HasCountedCommission.SqlIsNull()) && a.FatherMerchantGuid.SqlIsNotNull() && a.BeNn == 0, true, c => c.OrderTime, OrderMethods.ASC, LockType.Default, false);


                    if (list != null && list.Count > 0)
                    {
                        var listSys = querySys.GetList(c => c.MerchantGuid.SqlIn(list.Select(o => o.MerchantGuid.ToString()).Distinct().ToArray()) && c.ParameterName == ParameterName.Refund.RefundService_validity, isFilterMerchant: false);

                        var comList = new List<T_BAS_FlagshipCommission>();

                        //遍历订单
                        list.GroupBy(o => o.OrderGuid).ToList().ForEach(d =>
                        {
                            var currOr = d.First();

                            if (listSys != null && listSys.Count > 0)
                            {
                                var currPar = listSys.FirstOrDefault(c => c.MerchantGuid == currOr.MerchantGuid);
                                if (currPar != null && (!string.IsNullOrEmpty(currPar.ParameterValue)))
                                {
                                    var fixDay = int.Parse(currPar.ParameterValue);
                                    if (DateTimeEx.DateDiff(currOr.CompletedTime.Value) < fixDay)
                                    {
                                        return;
                                    }
                                }
                            }

                            var detailSum = d.Sum(c => c.WXPayMoney);

                            //当前订单的代理规则
                            var ruleEntity = new T_BAS_FlagshipOrders()
                            {
                                OrderGuid = currOr.OrderGuid,
                                UserWeChatType = currOr.UserWeChatType,
                                GoodsDeliveryType = currOr.GoodsDeliveryType,
                                CommodityRefundAudit = currOr.CommodityRefundAudit,
                                AgentComType = currOr.AgentComType,
                                AgentComRatio = currOr.AgentComRatio,
                            };
                            //记录当前订单佣金
                            comList.Add(new T_BAS_FlagshipCommission()
                            {
                                FlagshipCommissionGuid = Guid.NewGuid(),
                                MerchantGuid = currOr.MerchantGuid,
                                SMerchantGuid = currOr.MerchantGuid,
                                OrderGuid = currOr.OrderGuid,
                                PayMoney = detailSum,
                                AgentComType = ruleEntity.AgentComType,
                                AgentComRatio = ruleEntity.AgentComRatio,
                                CommMoney = decimal.Round((detailSum * ruleEntity.AgentComRatio / 100).Value, 2, MidpointRounding.AwayFromZero),
                                EntityState = EntityStates.ToBeAdd
                            });

                            //备用，待定
                            #region 返佣方式
                            //if (ruleEntity.AgentComType == AgentRuleConst.AgentComType.垂直返佣)
                            //{
                            //    query_FlagshipCommission.Add(new T_BAS_FlagshipCommission()
                            //    {
                            //        FlagshipCommissionGuid = Guid.NewGuid(),
                            //        MerchantGuid = currOr.MerchantGuid,
                            //        OrderGuid = currOr.OrderGuid,
                            //        PayMoney = detailSum,
                            //        AgentComType = ruleEntity.AgentComType,
                            //        AgentComRatio = ruleEntity.AgentComRatio,
                            //        CommMoney = detailSum * ruleEntity.AgentComRatio / 100
                            //    });
                            //}
                            //else if (ruleEntity.AgentComType == AgentRuleConst.AgentComType.全线分红)
                            //{
                            //    query_FlagshipCommission.Add(new T_BAS_FlagshipCommission()
                            //    {
                            //        FlagshipCommissionGuid = Guid.NewGuid(),
                            //        MerchantGuid = currOr.MerchantGuid,
                            //        OrderGuid = currOr.OrderGuid,
                            //        PayMoney = detailSum,
                            //        AgentComType = ruleEntity.AgentComType,
                            //        AgentComRatio = ruleEntity.AgentComRatio,
                            //        CommMoney = detailSum * ruleEntity.AgentComRatio / 100
                            //    });
                            //} 
                            #endregion

                        });

                        tran.BeginTransaction();
                        //批量保存订单佣金数据，并将所有已操作的订单更新为已计算
                        if (comList != null && comList.Count > 0)
                        {
                            query_FlagshipCommission.AddList(comList);

                            query_fsOrder.Update(c => new object[] { 
                             c.HasCountedCommission==true,
                             c.CountedCommissionTime==DateTime.Now
                            }, c => c.OrderGuid.SqlIn(comList.Select(m => m.OrderGuid).Distinct().ToArray()), isFilterMerchant: false);
                        }


                        //补充：将所有已操作订单佣金列表进行账户流水处理 
                        if (comList != null && comList.Count > 0)
                        {
                            var fcaList = new List<T_BAS_FactorageAccount>();
                            //var merList = query_mer.GetList(m => m.MerchantGuid.SqlIn(comList.Select(c => c.MerchantGuid.ToString()).Distinct().ToArray()), isFilterMerchant: false);
                            var merList = query_mer.GetList(isFilterMerchant: false);
                            var shar_fcaList = new List<T_BAS_FactorageAccount>();

                            //统计商家流水，暂定
                            comList.GroupBy(m => m.MerchantGuid).ToList().ForEach(o =>
                            {
                                var merchant = o.First().MerchantGuid;
                                var orderSumBal = o.Sum(c => c.CommMoney);
                                //var available = 0m;
                                //var freeze = 0m;
                                //AgentCommissionManage.GetAvailableAndFreeze(o.First().MerchantGuid, ref available, ref freeze);
                                //var currBalance = available + (orderSumBal ?? 0);
                                var currMer = merList.First(m => m.MerchantGuid == merchant);
                                currMer.FsBalance = (currMer.FsBalance ?? 0M) + orderSumBal;
                                currMer.EntityState = EntityStates.ToBeUpdated;

                                //添加该商家的对应账户流水
                                var tempGuid = Guid.NewGuid();
                                var codeDate = DateTime.Now;

                                fcaList.Add(new T_BAS_FactorageAccount()
                                {
                                    FactorageAccountGuid = tempGuid,
                                    MerchantGuid = merchant,
                                    SMerchantGuid = merchant,
                                    TradingCode = codeDate.ToString("yyyyMMddHHmmss") + string.Format("{0:D2}", AgentCommissionConst.TradingType.分红佣金),
                                    AvailableBalance = currMer.FsBalance,
                                    TradingType = AgentCommissionConst.TradingType.分红佣金,
                                    FactorageSubjectGuid = merchant,
                                    TradingAmount = orderSumBal,
                                    TradingDate = DateTime.Now,
                                    EntityState = EntityStates.ToBeAdd,
                                    Remark = "SELF"
                                });

                                //将当前流水单关联到对应的多个佣金订单 
                                query_FlagshipCommission.Update(c => new object[] { 
                                    c.FactorageAccountGuid==tempGuid, 
                                }, c => c.OrderGuid.SqlIn(o.ToArray().Select(m => m.OrderGuid).ToArray()), isFilterMerchant: false);


                                #region 处理当前商家的（可能）全线分红，计算全线共享流水 暂定处理
                                var tradeDate = DateTime.Now;
                                var i = 0;
                                var coEntity = o.OrderBy(c => c.AgentComRatio).FirstOrDefault(c => c.AgentComType == AgentRuleConst.AgentComType.全线分红);
                                if (coEntity != null && coEntity.AgentComRatio > 0)
                                {
                                    var shareAgents = AgentAuditManage.GetGroupAgentByMerGuid(merchant.Value).Where(c => c.MerchantGuid != merchant);
                                    //var shareAgents = AgentAuditManage.GetAllSubordinateAgentByMerGuid(MerchantManage.GetTopAgent(merchant.Value, tran).MerchantGuid).Where(c => c != merchant);
                                    if (shareAgents != null && shareAgents.Count() > 0)
                                    {
                                        #region 处理双向分红
                                        shareAgents.ToList().ForEach(m =>
                                        {
                                            var shareComList = comList.Where(c => c.MerchantGuid == m.MerchantGuid);
                                            if (shareComList.Any())
                                            {
                                                var paySum = shareComList.Sum(c => c.PayMoney);
                                                var moneySum = decimal.Round((paySum * coEntity.AgentComRatio / 100).Value, 2, MidpointRounding.AwayFromZero);

                                                if (paySum > 0 && moneySum > 0)
                                                {
                                                    currMer.FsBalance = (currMer.FsBalance ?? 0) + moneySum;
                                                    currMer.EntityState = EntityStates.ToBeUpdated;

                                                    shar_fcaList.Add(new T_BAS_FactorageAccount()
                                                     {
                                                         FactorageAccountGuid = Guid.NewGuid(),
                                                         MerchantGuid = merchant,
                                                         SMerchantGuid = merchant,
                                                         TradingCode = codeDate.ToString("yyyyMMddHHmmss") + string.Format("{0:D2}", AgentCommissionConst.TradingType.分红佣金),
                                                         AvailableBalance = currMer.FsBalance,
                                                         TradingType = AgentCommissionConst.TradingType.分红佣金,
                                                         FactorageSubjectGuid = m.MerchantGuid,
                                                         TradingAmount = moneySum,
                                                         TradingDate = tradeDate.AddSeconds(++i),
                                                         EntityState = EntityStates.ToBeAdd,
                                                         Remark = "SHARE"
                                                     });
                                                }

                                            }
                                            else
                                            {
                                                var shareCoEntity = AgentRulesManage.GetUnifyFlagshipParaByMer(m.MerchantGuid.Value);
                                                if (shareCoEntity == null || shareCoEntity.AgentComRatio == 0)
                                                {
                                                    return;
                                                }
                                                var currMerPaySum = comList.Where(c => c.MerchantGuid == currMer.MerchantGuid).Sum(c => c.PayMoney);
                                                var currMerMoneySum = decimal.Round((currMerPaySum * shareCoEntity.AgentComRatio / 100).Value, 2, MidpointRounding.AwayFromZero);
                                                if (currMerPaySum > 0 && currMerMoneySum > 0)
                                                {
                                                    var currShare = merList.First(c => c.MerchantGuid == m.MerchantGuid);

                                                    currShare.FsBalance = (currShare.FsBalance ?? 0) + currMerMoneySum;
                                                    currShare.EntityState = EntityStates.ToBeUpdated;

                                                    shar_fcaList.Add(new T_BAS_FactorageAccount()
                                                    {
                                                        FactorageAccountGuid = Guid.NewGuid(),
                                                        MerchantGuid = currShare.MerchantGuid,
                                                        SMerchantGuid = currShare.MerchantGuid,
                                                        TradingCode = codeDate.ToString("yyyyMMddHHmmss") + string.Format("{0:D2}", AgentCommissionConst.TradingType.分红佣金),
                                                        AvailableBalance = currShare.FsBalance,
                                                        TradingType = AgentCommissionConst.TradingType.分红佣金,
                                                        FactorageSubjectGuid = currMer.MerchantGuid,
                                                        TradingAmount = currMerMoneySum,
                                                        TradingDate = tradeDate.AddSeconds(++i),
                                                        EntityState = EntityStates.ToBeAdd,
                                                        Remark = "SHARE"
                                                    });
                                                }
                                            }

                                        });

                                        #endregion
                                    }
                                }

                                #endregion

                            });

                            //批量保存账户流水
                            if (shar_fcaList.Count > 0)
                            {
                                fcaList.AddRange(shar_fcaList);
                            }
                            if (fcaList.Count > 0)
                            {
                                query_FactorageAccount.AddList(fcaList);
                            }
                            if (merList.Count > 0)
                            {
                                query_mer.UpdateList(merList);
                            }
                        }

                        tran.Commit();
                    }

                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    Wechat.LogManage.Log("代理商商品佣金统计（代理分红模式）出错：" + ex.Message);
                }
            }
        }
        #endregion


        public static Guid? GetMember(Guid distributionPropGuid)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                var model = query.GetFirstData(a => a.DistributionPropGuid == distributionPropGuid, isFilterMerchant: false);
                return model == null ? null : model.MemberGuid;
            }
        }
        /// <summary>
        /// 更新分销订单表
        /// </summary>
        /// <param name="tran"></param>
        /// <param name="query_distribute"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static Result UpdateDistributionOrder(SqlRTransaction tran, IQuery<T_BAS_Distribute> query_distribute, T_BAS_Distribute model)
        {
            try
            {
                query_distribute.Update(model, false);
                return new Result(true);
            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }

        public static T_BAS_Member GetPropMember(Guid? distributionPropGuid)
        {
            if (distributionPropGuid == null)
                return null;
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_DistributionProp(tran);
                var model = query.GetFirstData(a => a.DistributionPropGuid == distributionPropGuid);
                if (model != null)
                {

                    var queryMember = Factory.CreateT_BAS_Member(tran);
                    return queryMember.GetFirstData(a => a.MemberGuid == model.MemberGuid);
                }
                else
                {
                    return null;
                }
            }
        }
        public static T_BAS_Member GetPropMemberNotFilter(Guid? distributionPropGuid)
        {
            if (distributionPropGuid == null)
                return null;
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_DistributionProp(tran);
                var model = query.GetFirstData(a => a.DistributionPropGuid == distributionPropGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                if (model != null)
                {

                    var queryMember = Factory.CreateT_BAS_Member(tran);
                    return queryMember.GetFirstData(a => a.MemberGuid == model.MemberGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                }
                else
                {
                    return null;
                }
            }
        }

        public static T_BAS_Member GetMemberInfo(Guid guid)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_DistributionProp(tran);
                var query_member = Factory.CreateT_BAS_Member(tran);
                var model = query.GetFirstData(a => a.DistributionPropGuid == guid);
                if (model != null && model.MemberGuid != null)
                {
                    return query_member.GetFirstData(a => a.MemberGuid == model.MemberGuid.Value);
                }
                else
                {
                    return null;
                }
            }
        }

        public static List<PT_BAS_Distribution_OrderDetail> GetPageList(Guid orderGuid, Guid merchantGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_OrderDetails(tran);
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_orderDetail = Factory.CreateProcedure(tran);
                var model = query_order.GetFirstData(a => a.OrderGuid == orderGuid && a.MerchantGuid == merchantGuid);
                List<PT_BAS_Distribution_OrderDetail> list_orderDetail = new List<PT_BAS_Distribution_OrderDetail>();
                List<T_BAS_OrderDetails> list = query.GetList(a => a.OrderGuid == orderGuid);
                foreach (T_BAS_OrderDetails item in list)
                {
                    var model_orderDetail = query_orderDetail.GetDistribution_OrderDetail(item.OrderDetailGuid);
                    model_orderDetail.Discount = item.Discount == null ? 0m : item.Discount.Value;
                    model_orderDetail.IntegralMoney = (item.IntegralMoney ?? 0);
                    model_orderDetail.DiscountPrice = item.DiscountPrice == null || item.DiscountPrice == 0.0m ? 1 : item.DiscountPrice.Value;
                    model_orderDetail.WXPayMoney = item.WXPayMoney == null ? item.Amount.Value : item.WXPayMoney.Value;

                    list_orderDetail.Add(model_orderDetail);
                }

                if (model.ProductClassify == 3)
                {
                    //处理运费返佣 zhou 2016/4/6 16:58
                    if (model.Freight != null && model.Freight > 0 && model.IsDistribute == true)
                    {
                        var distorder = Factory.CreateT_BAS_Distribute(tran).GetFirstData(a => a.OrderGuid == model.OrderGuid);
                        var distorderdetail = new PT_BAS_Distribution_OrderDetail()
                        {
                            ProductName = "运费返佣",
                            Price = model.Freight.Value,
                            Quantity = 1,
                            Amount = model.Freight.Value,
                            Discount = 0,
                            DiscountPrice = 1,
                            IntegralMoney = 0,
                            firstCommissionAmount = string.Format("{0}({1}%)", (model.Freight.Value * model.FreightFirstCom.Value).ToString("0.00"), (model.FreightFirstCom.Value * 100).ToString("0.00")),
                        };
                        if (distorder != null)
                        {
                            if (distorder.SuperiorDistributorGuid != null)
                                distorderdetail.secondCommissionAmount = string.Format("{0}({1}%)", (model.Freight.Value * model.FreightSecondCom.Value).ToString("0.00"), (model.FreightSecondCom.Value * 100).ToString("0.00"));
                            if (distorder.TopDistributorGuid != null)
                                distorderdetail.thirdCommissionAmount = string.Format("{0}({1}%)", (model.Freight.Value * model.FreightThirdCom.Value).ToString("0.00"), (model.FreightThirdCom.Value * 100).ToString("0.00"));

                        }
                        list_orderDetail.Add(distorderdetail);
                    }
                }
                return list_orderDetail;
            }
        }
        /// <summary>
        /// 根据状态获取分销订单商品统计
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <returns></returns>
        public static PT_BAS_Distribution_TotalOrders GetTotal(Guid DistributionPropGuid, int OrderInnerState)
        {
            using (var query = Factory.CreateProcedure())
            {
                return query.GetDistribution_TotalOrders(Common.CurrentManage.MerchantGuid, DistributionPropGuid, OrderInnerState);
            }
        }
        /// <summary>
        /// 获取所有分销订单商品统计
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <returns></returns>
        public static PT_BAS_Distribution_TotalOrders GetTotal(Guid DistributionPropGuid)
        {
            using (var query = Factory.CreateProcedure())
            {
                return query.GetDistribution_TotalOrders(Common.CurrentManage.MerchantGuid, DistributionPropGuid);
            }
        }

        /// <summary>
        /// 获取成功提现金额
        /// </summary>
        /// <param name="DistributionPropGuid"></param>
        /// <returns></returns>
        public static decimal GetTotalMoney(Guid DistributionPropGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_WithdrawsCommission(tran);
                List<T_BAS_WithdrawsCommission> list = query.GetList(a => a.DistributionPropGuid == DistributionPropGuid && a.State == 1);
                if (list.Count > 0)
                {
                    var amount = list.Sum(a => a.ApplyAmount);
                    return amount == null ? 0 : amount.Value;
                }
                else
                {
                    return 0;
                }

            }
        }
        /// <summary>
        /// 获取未结算、已结算分销佣金
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <returns></returns>
        public static decimal GetTotal(Guid DistributionPropGuid, bool isSettlement)
        {
            using (var tran = new SqlRTransaction())
            {

                var query = Factory.CreateProcedure(tran);
                return query.GetTotalAmount(DistributionPropGuid, isSettlement);
            }
        }

        /// <summary>
        /// 根据状态获取分销订单列表
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <returns></returns>
        public static List<PT_BAS_Distribution_List_Level> GetDistributionList(Guid DistributionPropGuid, int OrderInnerState)
        {
            using (var query = Factory.CreateProcedure())
            {
                return query.GetDistribution_List(OrderInnerState, DistributionPropGuid, Common.CurrentManage.MerchantGuid);
            }
        }
        /// <summary>
        /// 获取所有分销订单列表
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <returns></returns>
        public static List<PT_BAS_Distribution_List_Level> GetDistributionList(Guid DistributionPropGuid)
        {
            using (var query = Factory.CreateProcedure())
            {
                return query.GetDistribution_List(DistributionPropGuid, Common.CurrentManage.MerchantGuid);
            }
        }
        /// <summary>
        /// 获取所有分销订单列表(佣金)按等级
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <returns></returns>
        public static List<PT_BAS_Distribute_List_Level> GetDistribute_List(int level)
        {
            using (var query = Factory.CreateProcedure())
            {
                string did = CookieManage.GetCookie(SessionKeys.ShareDistribution);
                if (string.IsNullOrEmpty(did))
                    return null;
                var list = query.GetDistribute_List(Guid.Parse(did), Common.CurrentManage.MerchantGuid, level);
                return list;
            }
        }
        /// <summary>
        /// 获取所有分销订单数量(佣金)按等级
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <returns></returns>
        public static int GetDistribute_Count(int level)
        {
            using (var query = Factory.CreateProcedure())
            {
                string did = CookieManage.GetCookie(SessionKeys.ShareDistribution);
                if (string.IsNullOrEmpty(did))
                    return 0;
                var list = query.GetDistribute_List(Guid.Parse(did), Common.CurrentManage.MerchantGuid, level);
                return list.Count;
            }
        }
        /// <summary>
        /// 获取所有分销订单列表(佣金)
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <returns></returns>
        public static List<PT_BAS_Distribute_List_Level> GetDistribute_List()
        {
            using (var query = Factory.CreateProcedure())
            {
                string did = CookieManage.GetCookie(SessionKeys.ShareDistribution);
                if (string.IsNullOrEmpty(did))
                    return null;
                return query.GetDistribute_List(Guid.Parse(did), Common.CurrentManage.MerchantGuid, 0);
            }
        }

        /// <summary>
        /// 根据会员编号获取分销会员属性
        /// </summary>
        /// <param name="MemberGuid">MemberGuid</param>
        /// <returns></returns>
        public static T_BAS_DistributionProp GetDistributionProp(Guid MemberGuid)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetFirstData(a => a.MemberGuid == MemberGuid);
            }
        }

        /// <summary>
        /// 根据分销编号获取分销会员属性[重载,小号调用2015/08/15]
        /// </summary>
        /// <param name="distributionPropGuid"></param>
        /// <returns></returns>
        public static T_BAS_DistributionProp GetDistributionPropToProp(Guid distributionPropGuid)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetFirstData(a => a.DistributionPropGuid == distributionPropGuid);
            }
        }

        /// <summary>
        /// 获取上级分销商Guid
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <param name="orderGuid"></param>
        /// <returns></returns>
        public static Guid? GetSuperiorDistributorGuid(Guid? DistributionPropGuid, Guid orderGuid)
        {
            if (DistributionPropGuid == null) return null;
            //using (var query_order = Factory.CreateT_BAS_Orders())
            using (var query_order = Factory.CreateT_BAS_DistributionProp())
            {
                var dist = query_order.GetFirstData(a => a.DistributionPropGuid == DistributionPropGuid);
                return dist == null ? null : (Guid?)dist.ParentDistributionPropGuid;
            }
        }
        /// <summary>
        /// 获取上级分销商Guid
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <param name="orderGuid"></param>
        /// <returns></returns>
        public static Guid? GetSuperiorDistributorGuid(Guid merchantguid, Guid? DistributionPropGuid, Guid orderGuid)
        {
            if (DistributionPropGuid == null) return null;
            //using (var query_order = Factory.CreateT_BAS_Orders())
            using (var query_order = Factory.CreateT_BAS_DistributionProp())
            {
                var dist = query_order.GetFirstData(a => a.DistributionPropGuid == DistributionPropGuid && a.SMerchantGuid == merchantguid, isFilterMerchant: false);
                return dist == null ? null : (Guid?)dist.ParentDistributionPropGuid;
            }
        }

        /// <summary>
        /// 获取上级分销商Guid
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <param name="orderGuid"></param>
        /// <returns></returns>
        public static Guid? GetSuperiorDistributorGuid(Guid? DistributionPropGuid, Guid orderGuid, int level, Guid? merchantGuid = null)
        {
            if (DistributionPropGuid == null) return null;
            Guid? guid = null;
            //using (var query_order = Factory.CreateT_BAS_Orders())
            using (var query_order = Factory.CreateT_BAS_Distribute())
            {
                if (merchantGuid == null)
                {
                    merchantGuid = CurrentManage.MerchantGuid;
                }
                //var dist = query_order.GetFirstData(a => a.DistributionPropGuid == DistributionPropGuid && a.OrderGuid == orderGuid  );
                var dist = query_order.GetFirstData(a => a.DistributionPropGuid == DistributionPropGuid && a.OrderGuid == orderGuid && a.SMerchantGuid == merchantGuid, isFilterMerchant: false);
                switch (level)
                {
                    case 2:
                        guid = dist == null ? null : (Guid?)dist.SuperiorDistributorGuid;
                        break;
                    case 3:
                        guid = dist == null ? null : (Guid?)dist.TopDistributorGuid;
                        break;
                }
            }
            return guid;
        }


        /// <summary>
        /// 获取上上级分销商Guid
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <param name="orderGuid"></param>
        /// <returns></returns>
        public static Guid? GetTopDistributorGuid(Guid? DistributionPropGuid, Guid orderGuid)
        {
            if (DistributionPropGuid == null) return null;
            using (var query_order = Factory.CreateT_BAS_DistributionProp())
            {

                var dist = query_order.GetFirstData(a => a.ParentDistributionPropGuid == DistributionPropGuid);
                if (dist == null)
                    return null;
                else
                {
                    var dist2 = query_order.GetFirstData(a => a.ParentDistributionPropGuid == dist.DistributionPropGuid);
                    return dist2 == null ? null : (Guid?)dist2.DistributionPropGuid;
                }
            }
        }
        #region 获取分销订单记录条数
        /// <summary>
        /// 获取分销订单记录条数
        /// </summary>
        /// <param name="MemberGuid"></param>
        /// <returns></returns>
        public static int GetCount(Guid DistributionPropGuid, Guid MerchantGuid)
        {
            using (var query = Factory.CreateProcedure())
            {
                PT_BAS_Distribution_TotalOrders entity = query.GetDistribution_TotalOrders(MerchantGuid, DistributionPropGuid);
                if (entity == null)
                    return 0;
                else
                    return entity.OrderCount;
            }
        }
        #endregion

        #region
        public static T_BAS_DistributionProp GetEntityByMember(Guid memberGuid)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetFirstData(c => c.MemberGuid == memberGuid);
            }
        }
        #endregion

        public static T_BAS_DistributionProp GetEntityByDid(Guid? did)
        {
            if (did != null)
            {
                using (var query = Factory.CreateT_BAS_DistributionProp())
                {
                    return query.GetDataByGuid(did.Value);
                }
            }
            else
            {
                return null;
            }
        }
        public static string GetHeadStore(Guid did)
        {
            var DistributionStoreInfo = ParameterManage.GetParam(ParameterName.DistributionMemeber.DistributionStoreInfo);
            if (DistributionStoreInfo != null)
            {
                if (DistributionStoreInfo.ParameterValue.ToLower() == RFrameGenerate.BLL.DictionaryConst.DistributionStoreInfo.Disable.ToString())
                {
                    //分销商自定义店铺名称和Logo:
                    using (var query = Factory.CreateT_BAS_Merchants())
                    {
                        var merch = query.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid, isFilterMerchant: false);
                        return merch.StoreTitle;
                    }
                }
            }
            return DistributionManage.GetStoreTitle(did);
        }

        public static StoreInfo GetStoreInfo()
        {
            var DistributionStoreInfo = ParameterManage.GetParam(ParameterName.DistributionMemeber.DistributionStoreInfo);
            if (DistributionStoreInfo != null)
            {
                if (DistributionStoreInfo.ParameterValue.ToLower() == RFrameGenerate.BLL.DictionaryConst.DistributionStoreInfo.Disable.ToString())
                {
                    //分销商自定义店铺名称和Logo:
                    using (var query = Factory.CreateT_BAS_Merchants())
                    {
                        var merch = query.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid, isFilterMerchant: false);
                        return new StoreInfo() { Logo = merch.StoreLogo, SotreTitle = merch.StoreTitle };
                    }
                }
            }

            string storeTitle = "";
            string storeLogo = "";

            Guid? did = null;
            string strdid = CookieManage.GetCookie(SessionKeys.ShareDistribution);
            if (string.IsNullOrEmpty(strdid) != true)
            {
                did = Guid.Parse(strdid);
            }
            if (did == null)
            {
                using (var query = Factory.CreateT_BAS_Merchants())
                {
                    var merch = query.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                    return new StoreInfo() { Logo = merch.StoreLogo, SotreTitle = merch.StoreTitle };
                }
            }
            else
            {
                using (var tran = new SqlRTransaction())
                {
                    var querymem = Factory.CreateT_BAS_Member(tran);
                    var querydis = Factory.CreateT_BAS_DistributionProp(tran);

                    var dis = querydis.GetFirstData(a => a.DistributionPropGuid == did);
                    if (dis == null)
                    {//出错,返回商家店
                        CookieManage.SetCookie(SessionKeys.ShareDistribution, null, 1);
                        using (var query = Factory.CreateT_BAS_Merchants())
                        {
                            var merch = query.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                            return new StoreInfo() { Logo = merch.StoreLogo, SotreTitle = merch.StoreTitle };
                        }
                    }
                    else if (dis.IsEnable == false)
                    {
                        CookieManage.SetCookie(SessionKeys.ShareDistribution, null, 1);
                        using (var query = Factory.CreateT_BAS_Merchants())
                        {
                            var merch = query.GetFirstData(a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                            return new StoreInfo() { Logo = merch.StoreLogo, SotreTitle = merch.StoreTitle };
                        }
                    }
                    else
                    {
                        var user = querymem.GetFirstData(a => a.MemberGuid == dis.MemberGuid);

                        storeTitle = string.IsNullOrEmpty(dis.StoreTitle) ? dis.DistributionName + "的小店" : dis.StoreTitle;
                        if (string.IsNullOrEmpty(dis.StoreLogo) != true && dis.StoreLogo.Contains("http") != true)
                            dis.StoreLogo = CurrentManage.CurrentDomainWx + dis.StoreLogo;
                        storeLogo = string.IsNullOrEmpty(dis.StoreLogo) ? user.HeadImgUrl : dis.StoreLogo;

                        return new StoreInfo() { SotreTitle = storeTitle, Logo = storeLogo };
                    }
                }
            }
        }
        /// <summary>
        /// 根据分销商属性Guid获取店铺名称
        /// </summary>
        /// <param name="did"></param>
        /// <returns></returns>
        public static string GetStoreTitle(Guid did)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                var model = query.GetFirstData(a => a.DistributionPropGuid == did);
                if (model != null)
                    return string.IsNullOrEmpty(model.StoreTitle) ? model.DistributionName + "的小店" : model.StoreTitle;
                else
                    return "";
            }
        }
        public static T_BAS_DistributionProp GetStoreInfo(Guid did)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetFirstData(a => a.DistributionPropGuid == did);
            }
        }
        public static T_BAS_DistributionProp GetDistributeionProp(Guid distributionPropGuid)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetFirstData(a => a.DistributionPropGuid == distributionPropGuid, isFilterMerchant: false);
            }
        }

        public static T_BAS_DistributionProp GetDistributionPropByApplyGuid(Guid ParentMemberGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                var queryprop = Factory.CreateT_BAS_DistributionProp(tran);

                return queryprop.GetFirstData(a => a.MemberGuid == ParentMemberGuid);
            }
        }
        /// <summary>
        /// 修改店铺信息
        /// </summary>
        /// <param name="storeTitle"></param>
        /// <param name="storeLogo"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static Result SaveStoreInfo(T_BAS_DistributionProp entity)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                try
                {
                    var model = query.GetFirstData(a => a.DistributionPropGuid == entity.DistributionPropGuid);
                    if (model == null) return new Result(false, "找不到该记录！");
                    model.StoreTitle = entity.StoreTitle;
                    model.StoreLogo = entity.StoreLogo;
                    model.DistributionName = entity.DistributionName;
                    model.DistributionTelphone = entity.DistributionTelphone;
                    query.Update(model);
                    //若分销商修改姓名则所有下级分销商的上级姓名也需更改
                    var list = query.GetList(a => a.ParentDistributionPropGuid == entity.DistributionPropGuid);
                    if (list != null && list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            item.SuperiorName = entity.DistributionName;
                            item.EntityState = EntityStates.ToBeUpdated;
                        }
                        query.UpdateList(list);
                    }
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }


        public static Result SaveDistriInfo(string distriName, string tel)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                try
                {
                    string strdid = CookieManage.GetCookie(SessionKeys.ShareDistribution);
                    if (string.IsNullOrEmpty(strdid) == true)
                        return new Result(false, "出错了");
                    Guid did = Guid.Parse(strdid);
                    query.Update(a => new object[]
                    {
                            a.DistributionTelphone==tel,
                            a.DistributionName==distriName
                     },
                        b => b.DistributionPropGuid == did);

                    //若分销商修改姓名则所有下级分销商的上级姓名也需更改
                    var list = query.GetList(a => a.ParentDistributionPropGuid == did);
                    if (list != null && list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            item.SuperiorName = distriName;
                            item.EntityState = EntityStates.ToBeUpdated;
                        }
                        query.UpdateList(list);
                    }
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }

        /// <summary>
        /// 直接成为分销商接口
        /// </summary>
        public static void AutoBecomeReseller(string inviteropenid, Guid? did)
        {
            if (CurrentManage.IsDistribution == true)
                return;
            Guid memberGuid = CurrentUser.GetCurrUserGuid();
            if (memberGuid == Guid.Empty)
                return;
            T_BAS_DistributionProp dEntity = null;
            T_BAS_ApplyDistributionRecords aEntity = null;
            var paramApp = ParameterManage.GetParameter(ParameterName.DistributionMemeber.AuditApproachNew, CurrentManage.MerchantGuid);
            if (paramApp != null && int.Parse(paramApp.ParameterValue) == DictionaryConst.ApproachNew.Withoutm)
            {
                var member = MemberManage.GetMemberByGuid(memberGuid);

                try
                {
                    using (var tran = new SqlRTransaction())
                    {
                        var queryMember = Factory.CreateT_BAS_Member(tran);
                        var query = Factory.CreateT_BAS_DistributionProp(tran);
                        //var inviterMember = queryMember.GetFirstData(a => a.MemberOpenID == inviteropenid);
                        //if (inviterMember != null || inviteropenid == "0")
                        {
                            //条件验证
                            var BaseAmount = ParameterManage.GetParam(RFrameGenerate.BLL.ParameterName.DistributionMemeber.BaseAmount);
                            if (BaseAmount != null)
                            {
                                var baseAmount = BaseAmount.ParameterValue != null ? int.Parse(BaseAmount.ParameterValue) : 0;
                                if (baseAmount > 0)
                                {
                                    var TotalPrice = OrderManage.GetTotalMoney();
                                    if (TotalPrice < baseAmount)
                                        return;
                                }
                            }

                            string SuperiorName = "总部";
                            if (did != null)
                            {
                                var queryDid = Factory.CreateT_BAS_DistributionProp(tran);
                                var didmodel = queryDid.GetFirstData(a => a.DistributionPropGuid == did);
                                if (didmodel != null)
                                    SuperiorName = didmodel.DistributionName;
                            }


                            var queryapply = Factory.CreateT_BAS_ApplyDistributionRecords(tran);
                            aEntity = queryapply.GetFirstData(a => a.MemberGuid == CurrentUser.GetCurrUserGuid());
                            if (aEntity == null || aEntity.State == DictionaryConst.Apply.None)
                            {

                                if (aEntity == null)
                                {
                                    aEntity = new T_BAS_ApplyDistributionRecords()
                                    {
                                        MemberGuid = memberGuid,
                                        DistributionName = member.MemberName,
                                        ApplyDistributionRecordsGuid = Guid.NewGuid(),
                                        Telphone = member.MemberMobilePhone,
                                        ApplyDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                        State = DictionaryConst.Apply.Pass,
                                        SuperiorName = SuperiorName,
                                        ParentMemberGuid = did,
                                        EntityState = EntityStates.ToBeAdd
                                    };
                                }

                                dEntity = new T_BAS_DistributionProp
                                {
                                    DistributionPropGuid = Guid.NewGuid(),
                                    MemberGuid = memberGuid,
                                    DistributionName = member.MemberName,
                                    DistributionTelphone = member.MemberMobilePhone,
                                    SubMemberNum = 0,
                                    JoinDateTime = DateTime.Now,
                                    SuperiorName = SuperiorName,
                                    DistributionAmount = 0,
                                    DistributionCommissions = 0,
                                    IsEnable = true,
                                    AmountFrozen = 0,
                                    ParentDistributionPropGuid = did,
                                    StoreLogo = "",
                                    StoreTitle = "",
                                    WithdrawalAmount = 0,
                                };
                                dEntity.RQCode = "/upload/qrcode/" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "/" + dEntity.DistributionPropGuid + ".jpg";

                                var qrcodeurl = "http://" + MerchantManage.GetDomain() + "/WxShop/Index?did=" + dEntity.DistributionPropGuid;
                                string filename = AppDomain.CurrentDomain.BaseDirectory + "upload\\qrcode\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + dEntity.DistributionPropGuid + ".jpg";
                                bool isCreate = QrCodeHelper.GenerationQrCode(qrcodeurl, "", filename);
                                dEntity.RQCode = "/upload/qrcode/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + dEntity.DistributionPropGuid + ".jpg";

                                tran.BeginTransaction();
                                if (aEntity.EntityState == EntityStates.ToBeAdd)
                                    queryapply.Add(aEntity);
                                else
                                {
                                    queryapply.Update(a => new object[]
                                { 
                                    a.State == DictionaryConst.Apply.Pass, 
                                    a.Telphone ==  member.MemberMobilePhone,
                                    a.DistributionName == member.MemberName,
                                    a.ParentMemberGuid==did, 
                                    a.ApplyDateTime==DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                                }, b => b.ApplyDistributionRecordsGuid == aEntity.ApplyDistributionRecordsGuid);
                                }
                                query.Add(dEntity);
                                queryMember.Update(a => new object[] { a.IsDistributor == true }, b => b.MemberGuid == memberGuid);

                                var result = DistributionManage.UpdataTeam(dEntity.DistributionPropGuid, tran);

                                if (result.State == true)
                                    tran.Commit();

                                CurrentUser.SetIsDistribution(true);
                                CurrentUser.SetDistributionGuid(dEntity.DistributionPropGuid);
                            }
                        }

                    }

                    if (dEntity != null && aEntity != null)
                    {
                        using (var tran = new SqlRTransaction())
                        {
                            #region 模板消息
                            try
                            {
                                var query = Factory.CreateT_BAS_DistributionProp(tran);
                                var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                                var merchGuid = HeadPay.GetPayMerchantGuid(CurrentManage.MerchantUserID);
                                var template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.分销商申请成功提醒, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                                if (template != null)
                                {
                                    Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                                    send.first = new Wechat.Model.TempateKey("first", "恭喜您已经成为分销商");
                                    send.keys = new List<Wechat.Model.TempateKey>();
                                    send.keys.Add(new Wechat.Model.TempateKey("keyword1", dEntity.DistributionName));
                                    send.keys.Add(new Wechat.Model.TempateKey("keyword2", dEntity.DistributionTelphone));
                                    send.keys.Add(new Wechat.Model.TempateKey("keyword3", aEntity.ApplyDateTime));
                                    send.remark = new Wechat.Model.TempateKey("remark", "如有疑问，请在微信中留言，我们将第一时间为您服务。");
                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenIDManage.GetOpenID(), template.TemplateID, CurrentManage.CurrentDomainWx + "DistributionCenter/Index", send, CurrentManage.AppId);
                                }
                                if (did != null)
                                {
                                    template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.新代理加入通知, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);

                                    if (template != null)
                                    {
                                        //上级
                                        var supDistribution = query.GetFirstData(a => a.DistributionPropGuid == dEntity.ParentDistributionPropGuid.Value);
                                        if (supDistribution != null)
                                        {
                                            var supMember = MemberManage.GetMemberByGuid(supDistribution.MemberGuid.Value);
                                            if (supMember != null)
                                            {
                                                Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                                                send.first = new Wechat.Model.TempateKey("first", "有一位新成员加入您的团队，赶紧去看看吧。");
                                                send.keys = new List<Wechat.Model.TempateKey>();
                                                send.keys.Add(new Wechat.Model.TempateKey("keyword1", dEntity.DistributionName));
                                                send.keys.Add(new Wechat.Model.TempateKey("keyword2", member.WeChatName));
                                                send.keys.Add(new Wechat.Model.TempateKey("keyword3", dEntity.DistributionTelphone));
                                                send.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。");

                                                weixinopen.WeiXinOpenRequest.SendMessageTemplate(supMember.MemberOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", CurrentManage.MerchantUserID)) + "DistributionCenter/Index", send, Common.CurrentManage.AppId);
                                            }

                                            //上上级
                                            if (supDistribution.ParentDistributionPropGuid != null)
                                            {
                                                var topDistribution = query.GetFirstData(a => a.DistributionPropGuid == supDistribution.ParentDistributionPropGuid.Value);
                                                if (topDistribution != null)
                                                {
                                                    var topMember = MemberManage.GetMemberByGuid(topDistribution.MemberGuid.Value);
                                                    if (topMember != null)
                                                    {
                                                        Wechat.Model.SendTempateKey sendTop = new Wechat.Model.SendTempateKey();
                                                        sendTop.first = new Wechat.Model.TempateKey("first", "有一位新成员加入您的团队，赶紧去看看吧。");
                                                        sendTop.keys = new List<Wechat.Model.TempateKey>();
                                                        sendTop.keys.Add(new Wechat.Model.TempateKey("keyword1", dEntity.DistributionName));
                                                        sendTop.keys.Add(new Wechat.Model.TempateKey("keyword2", member.WeChatName));
                                                        sendTop.keys.Add(new Wechat.Model.TempateKey("keyword3", dEntity.DistributionTelphone));
                                                        sendTop.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                        weixinopen.WeiXinOpenRequest.SendMessageTemplate(topMember.MemberOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", Common.CurrentManage.MerchantUserID)) + "DistributionCenter/Index", sendTop, Common.CurrentManage.AppId);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Wechat.LogManage.Log("成功分销商发送模板出错" + ex.Message);
                            }

                            #endregion
                        }
                    }
                }
                catch (Exception ex)
                {
                    Wechat.LogManage.Log("会员:" + memberGuid + ",上级:" + did + "自动成功分销商出错," + ex.Message);
                }
            }
        }

        public static string GetSupDistribution(Guid orderGuid, int level)
        {
            using (var tran = new SqlRTransaction())
            {
                string distributionInfo = "";
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_distributionProp = Factory.CreateT_BAS_DistributionProp(tran);
                var model_order = query_order.GetFirstData(a => a.OrderGuid == orderGuid);
                if (model_order == null && model_order.DistributionPropGuid == null)
                    return "";
                Guid? superiorDistributorGuid = null;
                superiorDistributorGuid = GetSuperiorDistributorGuid(model_order.DistributionPropGuid, orderGuid, 2);
                var model_sup = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == superiorDistributorGuid);

                var distributionVisible = ParameterManage.GetParam(ParameterName.DistributionMemeber.DistributionVisible);
                if (distributionVisible == null || string.IsNullOrEmpty(distributionVisible.ParameterValue))
                {
                    return model_sup == null ? "" : "<div class='dfh_title'>上级分销商：<span>" + model_sup.DistributionName + "</span></div>";
                }
                switch (int.Parse(distributionVisible.ParameterValue))
                {
                    case DictionaryConst.DistributionVisible.AllDisable:
                        distributionInfo = "";
                        break;
                    case DictionaryConst.DistributionVisible.AllEnable:
                        distributionInfo = model_sup == null ? "" : "<div class='dfh_title'>上级分销商：<span>" + model_sup.DistributionName + "(" + model_sup.DistributionTelphone + ")" + "</span></div>";
                        break;
                    case DictionaryConst.DistributionVisible.NameEnable:
                        distributionInfo = model_sup == null ? "" : "<div class='dfh_title'>上级分销商：<span>" + model_sup.DistributionName + "</span></div>";
                        break;
                    default:
                        distributionInfo = model_sup == null ? "" : "<div class='dfh_title'>上级分销商：<span>" + model_sup.DistributionName + "</span></div>";
                        break;
                }
                return distributionInfo;
            }
        }

        public static string GetTopDistribution(Guid orderGuid, int level)
        {
            using (var tran = new SqlRTransaction())
            {
                string distributionInfo = "";
                var query_order = Factory.CreateT_BAS_Orders(tran);
                var query_distributionProp = Factory.CreateT_BAS_DistributionProp(tran);
                var model_order = query_order.GetFirstData(a => a.OrderGuid == orderGuid);
                if (model_order == null && model_order.DistributionPropGuid == null)
                    return "";
                Guid? topDistributorGuid = null;

                topDistributorGuid = GetSuperiorDistributorGuid(model_order.DistributionPropGuid, orderGuid, 3);
                var model_top = query_distributionProp.GetFirstData(a => a.DistributionPropGuid == topDistributorGuid);

                var distributionVisible = ParameterManage.GetParam(ParameterName.DistributionMemeber.DistributionVisible);
                if (distributionVisible == null || string.IsNullOrEmpty(distributionVisible.ParameterValue))
                {
                    return model_top == null ? "" : "<div class='dfh_title'>上上级分销商：<span>" + model_top.DistributionName + "</span></div>";
                }
                switch (int.Parse(distributionVisible.ParameterValue))
                {
                    case DictionaryConst.DistributionVisible.AllDisable:
                        distributionInfo = "";
                        break;
                    case DictionaryConst.DistributionVisible.AllEnable:
                        distributionInfo = model_top == null ? "" : "<div class='dfh_title'>上上级分销商：<span>" + model_top.DistributionName + "(" + model_top.DistributionTelphone + ")" + "</span></div>";
                        break;
                    case DictionaryConst.DistributionVisible.NameEnable:
                        distributionInfo = model_top == null ? "" : "<div class='dfh_title'>上上级分销商：<span>" + model_top.DistributionName + "</span></div>";
                        break;
                    default:
                        distributionInfo = model_top == null ? "" : "<div class='dfh_title'>上上级分销商：<span>" + model_top.DistributionName + "</span></div>";
                        break;
                }
                return distributionInfo;
            }
        }
        
        public static List<T_BAS_DistributionProp> GetDistributionPropPageList(string topNumber)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                return query.GetTopData(topNumber, null, true, b => b.DistributionCommissions, OrderMethods.DESC, LockType.Default);
            }

        }

        public static Result UpdateDistributionQRCode(Guid did, string path)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                try
                {
                    query.Update(a => new Object[] { 
                        a.DistributionQRCode==path
                    }, a => a.DistributionPropGuid == did);
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }
        public static Result UpdateQRCodeParamImage(Guid did, string path)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                try
                {
                    query.Update(a => new Object[] { 
                        a.QRCodeParamImage==path
                    }, a => a.DistributionPropGuid == did);
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }
        /// <summary>
        /// 三级订单
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static Result GetDistributionOrders(Guid guid, ref string str)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    StringBuilder sb = new StringBuilder();
                    //var query_order = Factory.CreateT_ST_DistributeOrder(tran);
                    //处理运费返佣 zhou 2016/4/6 16:58
                    var query_order = Factory.CreateProcedure(tran);
                    var query = Factory.CreateT_BAS_Distribute(tran);
                    var query_prop = Factory.CreateT_BAS_DistributionProp(tran);

                    //var model_order = query_order.GetFirstData(a => a.DistributeGuid == guid);
                    var model_order = query_order.GetDistribution_Order(guid);

                    if (model_order == null) return new Result(false, "该数据不存在！");
                    if (model_order.DistributionPropGuid == null || model_order.DistributeGuid == Guid.Empty) return new Result(false, "该数据不存在！");

                    T_BAS_DistributionProp model = null;
                    T_BAS_DistributionProp model_sup = null;
                    T_BAS_DistributionProp model_top = null;

                    //一级
                    model = query_prop.GetFirstData(a => a.DistributionPropGuid == model_order.DistributionPropGuid);
                    //二级
                    if (model_order.SuperiorDistributorGuid != null && model_order.SuperiorDistributorGuid != Guid.Empty)
                    {
                        model_sup = query_prop.GetFirstData(a => a.DistributionPropGuid == model_order.SuperiorDistributorGuid);
                    }
                    //三级
                    if (model_order.TopDistributorGuid != null && model_order.TopDistributorGuid != Guid.Empty)
                    {
                        model_top = query_prop.GetFirstData(a => a.DistributionPropGuid == model_order.TopDistributorGuid);
                    }
                    #region 一级
                    if (model != null)
                    {
                        var first = (model_order.FirstCommission.Value).ToString("0.00");
                        sb.Append("<tr data-guid='" + model_order.DistributeGuid + "'>");
                        sb.Append("<td align='center'>");
                        sb.Append("一级订单");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append(first);
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("" + GetStoreTitle(model.DistributionPropGuid) + "");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("" + model.DistributionName + "");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("" + model.DistributionTelphone + "");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("</tr>");
                    }
                    #endregion
                    #region 二级
                    if (model_sup != null)
                    {
                        var second = (model_order.SecondCommission.Value).ToString("0.00");
                        sb.Append("<tr data-guid='" + model_order.DistributeGuid + "'>");
                        sb.Append("<td align='center'>");
                        sb.Append("二级订单");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append(second);
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append(model_sup == null ? "" : GetStoreTitle(model_sup.DistributionPropGuid));
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append(model_sup == null ? model.SuperiorName : model_sup.DistributionName);
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append(model_sup == null ? "" : model_sup.DistributionTelphone);
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("</tr>");
                    }
                    #endregion
                    #region 三级
                    if (model_top != null)
                    {
                        var third = (model_order.ThirdCommission.Value).ToString("0.00");
                        sb.Append("<tr data-guid='" + model_order.DistributeGuid + "'>");
                        sb.Append("<td align='center'>");
                        sb.Append("三级订单");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append(third);
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append(model_top == null ? "" : GetStoreTitle(model_top.DistributionPropGuid));
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append(model_top == null ? (model_sup == null ? "" : model_sup.SuperiorName) : model_top.DistributionName);
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append(model_top == null ? "" : model_top.DistributionTelphone);
                        sb.Append("</td>");
                        sb.Append("<td   align='center'>");
                        sb.Append("");
                        sb.Append("</td>");
                        sb.Append("</tr>");
                    }
                    #endregion

                    str = sb.ToString();
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }

        public static T_BAS_ApplyDistributionRecords GetApplyDistributionRecord(Guid memberGuid)
        {
            using (var query = Factory.CreateT_BAS_ApplyDistributionRecords())
            {
                return query.GetFirstData(a => a.MemberGuid == memberGuid);
            }
        }
        public static Result ApplyDistributionRetry()
        {
            using (var query = Factory.CreateT_BAS_ApplyDistributionRecords())
            {
                query.Update(a => new object[] { a.State == DictionaryConst.Apply.None }, b => b.MemberGuid == CurrentUser.GetCurrUserGuid() && b.State == DictionaryConst.Apply.False);
                return new Result(true);
            }
        }
        public static Result ApplyDistribution(string distributionName, string telphone)
        {
            using (var tran = new SqlRTransaction())
            {
                tran.BeginTransaction();
                //条件验证
                var BaseAmount = ParameterManage.GetParam(RFrameGenerate.BLL.ParameterName.DistributionMemeber.BaseAmount);
                if (BaseAmount != null)
                {
                    var baseAmount = BaseAmount.ParameterValue != null ? int.Parse(BaseAmount.ParameterValue) : 0;
                    if (baseAmount > 0)
                    {
                        var TotalPrice = OrderManage.GetTotalMoney();
                        if (TotalPrice < baseAmount)
                            return new Result(false, "亲！您还未达到申请分销商要求喔！您只需在本店购买满" + baseAmount.ToString("0.00") + "元.");
                    }
                }
                //添加申请记录
                var queryapply = Factory.CreateT_BAS_ApplyDistributionRecords(tran);
                var apply = queryapply.GetFirstData(a => a.MemberGuid == CurrentUser.GetCurrUserGuid());
                if (apply == null || apply.State == DictionaryConst.Apply.None)
                {
                    try
                    {
                        var state = DictionaryConst.Apply.Waiting;
                        var AuditApproachNew = ParameterManage.GetParam(RFrameGenerate.BLL.ParameterName.DistributionMemeber.AuditApproachNew);
                        //系统审核
                        if (AuditApproachNew != null && AuditApproachNew.ParameterValue == DictionaryConst.ApproachNew.System.ToString())
                        {
                            state = DictionaryConst.Apply.Pass;
                        }
                        //string did = CookieManage.GetCookie(SessionKeys.ShareDistribution);
                        Guid? did = MemberManage.GetParentDID(OpenIDManage.GetOpenID());
                        if (did == CurrentManage.MerchantGuid)
                            did = null;

                        if (apply != null)
                        {
                            queryapply.Update(a => new object[]
                            { 
                                a.State == state, 
                                a.Telphone == telphone,
                                a.DistributionName == distributionName,
                                a.ApplyDateTime==DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                a.ParentMemberGuid==did
                            }, b => b.ApplyDistributionRecordsGuid == apply.ApplyDistributionRecordsGuid);
                        }
                        else
                        {
                            apply = new T_BAS_ApplyDistributionRecords();
                            apply.ParentMemberGuid = did;
                            apply.ApplyDistributionRecordsGuid = Guid.NewGuid();
                            apply.State = state;
                            apply.ApplyDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            apply.SuperiorName = DistributionManage.GetShareName();
                            apply.Telphone = telphone;
                            apply.DistributionName = distributionName;
                            apply.MemberGuid = CurrentUser.GetCurrUserGuid();
                            queryapply.Add(apply);
                        }
                        //系统审核
                        if (AuditApproachNew != null && AuditApproachNew.ParameterValue == DictionaryConst.ApproachNew.System.ToString())
                        {
                            //添加分销商
                            var queryProp = Factory.CreateT_BAS_DistributionProp(tran);
                            T_BAS_DistributionProp disEntity = new T_BAS_DistributionProp()
                            {
                                ParentDistributionPropGuid = did,
                                SubMemberNum = 0,
                                SuperiorName = DistributionManage.GetShareName(),
                                IsEnable = true,
                                DistributionName = distributionName,
                                DistributionTelphone = telphone,
                                JoinDateTime = DateTime.Now,
                                DistributionPropGuid = Guid.NewGuid(),
                                MemberGuid = CurrentUser.GetCurrUserGuid(),
                                DistributionAmount = 0,
                                WithdrawalAmount = 0,
                                DistributionCommissions = 0,
                                AmountFrozen = 0,
                                DistributionQRCode = null,
                                MarketingField = "",
                                QRCodeParamImage = null,
                                RQCode = null,
                                StoreLogo = null,
                                StoreTitle = null,
                            };
                            //二维码
                            var qrcodeurl = "http://" + MerchantManage.GetDomain() + "/WxShop/Index?did=" + disEntity.DistributionPropGuid;
                            string filename = AppDomain.CurrentDomain.BaseDirectory + "upload\\qrcode\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + disEntity.DistributionPropGuid + ".jpg";
                            bool isCreate = QrCodeHelper.GenerationQrCode(qrcodeurl, "", filename);
                            disEntity.RQCode = "/upload/qrcode/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + disEntity.DistributionPropGuid + ".jpg";
                            queryProp.Add(disEntity);

                            //更新会员
                            var queryMember = Factory.CreateT_BAS_Member(tran);
                            queryMember.Update(c => new object[]
                            {
                                c.IsDistributor == true,
                            }, a => a.MemberGuid == CurrentUser.GetCurrUserGuid());
                            //更新团队成员
                            DistributionManage.UpdataTeam(disEntity.DistributionPropGuid, tran);

                            CurrentUser.SetIsDistribution(true);
                            CurrentUser.SetDistributionGuid(disEntity.DistributionPropGuid);

                            //发送模板消息
                            #region 模板消息
                            try
                            {
                                var querytemp = Factory.CreateT_BAS_MessageTemplate(tran);
                                var merchGuid = HeadPay.GetPayMerchantGuid(CurrentManage.MerchantUserID);
                                var template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.分销商申请成功提醒, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                                if (template != null)
                                {
                                    Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                                    send.first = new Wechat.Model.TempateKey("first", "恭喜您已经成为分销商");
                                    send.keys = new List<Wechat.Model.TempateKey>();
                                    send.keys.Add(new Wechat.Model.TempateKey("keyword1", disEntity.DistributionName));
                                    send.keys.Add(new Wechat.Model.TempateKey("keyword2", disEntity.DistributionTelphone));
                                    send.keys.Add(new Wechat.Model.TempateKey("keyword3", apply.ApplyDateTime));
                                    send.remark = new Wechat.Model.TempateKey("remark", "如有疑问，请在微信中留言，我们将第一时间为您服务。");
                                    weixinopen.WeiXinOpenRequest.SendMessageTemplate(OpenIDManage.GetOpenID(), template.TemplateID, CurrentManage.CurrentDomainWx + "DistributionCenter/Index", send, CurrentManage.AppId);
                                }
                                template = querytemp.GetFirstData(a => a.MerchantGuid == merchGuid && a.TemplateNo == DictionaryConst.TemplateMessage.新代理加入通知, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                                if (template != null)
                                {
                                    if (disEntity.ParentDistributionPropGuid != null && disEntity.ParentDistributionPropGuid != Guid.Empty)
                                    {
                                        var memberGuid = CurrentUser.GetCurrUserGuid();
                                        var queryMem = Factory.CreateT_BAS_Member(tran);
                                        var member = queryMem.GetFirstData(a => a.MemberGuid == memberGuid);

                                        //上级
                                        var supDistribution = queryProp.GetFirstData(a => a.DistributionPropGuid == disEntity.ParentDistributionPropGuid.Value);
                                        if (supDistribution != null)
                                        {
                                            var supMember = MemberManage.GetMemberByGuid(supDistribution.MemberGuid.Value);
                                            if (supMember != null)
                                            {
                                                Wechat.Model.SendTempateKey send = new Wechat.Model.SendTempateKey();
                                                send.first = new Wechat.Model.TempateKey("first", "有一位新成员加入您的团队，赶紧去看看吧。");
                                                send.keys = new List<Wechat.Model.TempateKey>();
                                                send.keys.Add(new Wechat.Model.TempateKey("keyword1", disEntity.DistributionName));
                                                send.keys.Add(new Wechat.Model.TempateKey("keyword2", member.WeChatName));
                                                send.keys.Add(new Wechat.Model.TempateKey("keyword3", disEntity.DistributionTelphone));
                                                send.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。");

                                                weixinopen.WeiXinOpenRequest.SendMessageTemplate(supMember.MemberOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", CurrentManage.MerchantUserID)) + "DistributionCenter/Index", send, Common.CurrentManage.AppId);
                                            }

                                            //上上级
                                            if (supDistribution.ParentDistributionPropGuid != null)
                                            {
                                                var topDistribution = queryProp.GetFirstData(a => a.DistributionPropGuid == supDistribution.ParentDistributionPropGuid.Value);
                                                if (topDistribution != null)
                                                {
                                                    var topMember = MemberManage.GetMemberByGuid(topDistribution.MemberGuid.Value);
                                                    if (topMember != null)
                                                    {
                                                        Wechat.Model.SendTempateKey sendTop = new Wechat.Model.SendTempateKey();
                                                        sendTop.first = new Wechat.Model.TempateKey("first", "有一位新成员加入您的团队，赶紧去看看吧。");
                                                        sendTop.keys = new List<Wechat.Model.TempateKey>();
                                                        sendTop.keys.Add(new Wechat.Model.TempateKey("keyword1", disEntity.DistributionName));
                                                        sendTop.keys.Add(new Wechat.Model.TempateKey("keyword2", member.WeChatName));
                                                        sendTop.keys.Add(new Wechat.Model.TempateKey("keyword3", disEntity.DistributionTelphone));
                                                        sendTop.remark = new Wechat.Model.TempateKey("remark", "感谢您的使用,祝您生意兴隆。！");
                                                        weixinopen.WeiXinOpenRequest.SendMessageTemplate(topMember.MemberOpenID, template.TemplateID, CurrentManage.DomainWx.Replace("shop.", string.Format("{0}.shop.", Common.CurrentManage.MerchantUserID)) + "DistributionCenter/Index", sendTop, Common.CurrentManage.AppId);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Wechat.LogManage.Log("成功分销商发送模板出错" + ex.Message);
                            }

                            #endregion

                        }
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        return new Result(false, "申请出错了," + ex.Message);
                    }
                    return new Result(true);
                }
                else if (apply.State == DictionaryConst.AgentApplyState.AuditPass)
                {
                    return new Result(false, "您已经是分销商了,无需再次申请!");
                }
                else
                {
                    return new Result(false, "您已申请,请等待审核!");
                }
            }
        }


        public static string GetShowQRcode(string OpenID, Guid did)
        {
            string mappath = AppDomain.CurrentDomain.BaseDirectory;
            var mentity = DistributionManage.GetStoreInfo();
            var backgoundImage = MerchantManage.GetBackgroundImgae();
            var StoreShareType = ParameterMagage.GetStoreShareType();
            #region 店铺二维码
            if (StoreShareType == DictionaryConst.StoreShareType.Store)
            {
                string qrcodeImage = DistributionManage.ShowQRCode(OpenID);
                #region 绘制二维码
                if (RFrameGenerate.BLL.ParameterMagage.GetImageType() == RFrameGenerate.BLL.DictionaryConst.ImageDistributionType.Image)
                {
                    var prop = DistributionManage.GetDistributeionProp(did);
                    var paramApp = ParameterManage.GetParameter(ParameterName.DistributionMemeber.AuditApproachNew, CurrentManage.MerchantGuid);

                    //检查文件是否存在,不存在重新生成
                    if (string.IsNullOrEmpty(prop.DistributionQRCode) != true)
                    {
                        string savePath = mappath + "\\" + prop.DistributionQRCode.Replace("/", "\\").Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries)[0];
                        if (System.IO.File.Exists(savePath) != true)
                            prop.DistributionQRCode = string.Empty;
                    }


                    if (string.IsNullOrEmpty(prop.DistributionQRCode) ||
                        (paramApp != null && int.Parse(paramApp.ParameterValue) == DictionaryConst.ApproachNew.Withoutm))
                    {
                        string url = "";
                        string savePath = mappath + DictionaryConst.UpLoadPath.DistributionQR + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + prop.DistributionPropGuid + ".jpg";
                        try
                        {
                            if (GraphicHelper.MadeRQ(mentity.Logo, backgoundImage, qrcodeImage.Replace("/", "\\").Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries)[0], prop.DistributionName, mentity.SotreTitle, savePath))
                            {
                                url = DictionaryConst.UpLoadPath.DistributionQR + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + prop.DistributionPropGuid + ".jpg?v=" + DateTime.Now.Millisecond;
                                DistributionManage.UpdateDistributionQRCode(did, url);
                            }
                        }
                        catch (Exception ex)
                        {
                            Wechat.LogManage.Log("生成分销二维码异常:" + ex.Message);
                        }
                        return url;
                    }
                    else
                    {
                        return prop.DistributionQRCode;
                    }
                }
                #endregion
                #region 默认
                else
                {
                    return qrcodeImage;
                }
                #endregion
            }
            #endregion
            #region 带参数二维码
            else
            {
                var prop = DistributionManage.GetDistributeionProp(did);
                var paramApp = ParameterManage.GetParameter(ParameterName.DistributionMemeber.AuditApproachNew, CurrentManage.MerchantGuid);

                //检查文件是否存在,不存在重新生成
                if (string.IsNullOrEmpty(prop.DistributionQRCode) != true)
                {
                    string savePath = DictionaryConst.UpLoadPath.DistributionQR + "\\" + prop.DistributionQRCode.Replace("/", "\\").Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries)[0];
                    if (System.IO.File.Exists(savePath) != true)
                        prop.DistributionQRCode = string.Empty;
                }

                if (string.IsNullOrEmpty(prop.DistributionQRCode) ||
                    (paramApp != null && int.Parse(paramApp.ParameterValue) == DictionaryConst.ApproachNew.Withoutm))
                {
                    string url = "";
                    string savePath = DictionaryConst.UpLoadPath.DistributionQR + DictionaryConst.UpLoadPath.DistributionQRParam + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + prop.DistributionPropGuid + ".jpg";
                    try
                    {
                        if (string.IsNullOrEmpty(prop.QRCodeParamImage) == true)
                        {
                            Wechat.Model.QRCode qrcode = weixinopen.WeiXinOpenRequest.CreatePerpetualQRCode(did.ToString(), CurrentManage.AppId);
                            if (qrcode.state == true)
                            {

                                System.Drawing.Image image = weixinopen.WeiXinOpenRequest.GetQRCode(qrcode.ticket);
                                try
                                {
                                    if (System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(savePath)) != true)
                                        System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(savePath));
                                    image.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                                }
                                finally
                                {
                                    image.Dispose();
                                }
                                url = DictionaryConst.UpLoadPath.DistributionQRParam + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + prop.DistributionPropGuid + ".jpg?v=" + DateTime.Now.Millisecond;
                                DistributionManage.UpdateQRCodeParamImage(did, url);
                                prop.QRCodeParamImage = url;
                            }
                        }

                        savePath = DictionaryConst.UpLoadPath.DistributionQR + DictionaryConst.UpLoadPath.DistributionQR + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\" + prop.DistributionPropGuid + ".jpg";

                        //生成二维码
                        if (GraphicHelper.MadeRQ(mentity.Logo, backgoundImage, prop.QRCodeParamImage.Replace("/", "\\").Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries)[0], prop.DistributionName, mentity.SotreTitle, savePath))
                        {
                            url = DictionaryConst.UpLoadPath.DistributionQR + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + prop.DistributionPropGuid + ".jpg?v=" + DateTime.Now.Millisecond;
                            DistributionManage.UpdateDistributionQRCode(did, url);
                        }
                    }
                    catch (Exception ex)
                    {
                        Wechat.LogManage.Log("生成公众号带参数二维码异常:" + ex.Message);
                    }
                    return url;
                }
                else
                {
                    return prop.DistributionQRCode;
                }
            }
            #endregion
        }

        public static void UpdateMediaID(string imageMediaid, Guid did)
        {
            string info = string.Format("{0},{1}", imageMediaid, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                query.Update(a => new object[] { a.UploadImageMediaInfo == info }, b => b.DistributionPropGuid == did);
            }
        }

        public static decimal GetTotalCommission(Guid guid)
        {
            using (var query = Factory.CreateT_BAS_Distribute())
            {
                var model = query.GetFirstData(a => a.OrderGuid == guid);
                if (model == null) return 0M;
                return model.TotalCommission == null ? 0 : model.TotalCommission.Value;
            }
        }

        public static Result UpdateTitle(Guid did, string title)
        {
            using (var query = Factory.CreateT_BAS_DistributionProp())
            {
                query.Update(a => new object[] { a.StoreTitle == title }, b => b.DistributionPropGuid == did);
                return new Result(true);
            }
        }
    }
}
