using RFrameGenerate.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RFramework.SQLQuery;
using RFramework;
using RFramework.SQLServer;
using RFrameGenerate.Common;
using System.Linq.Expressions;
using RFrameGenerate.DAL.Enums;
using RFrameGenerate.DAL.Interface;
using RFrameGenerate.Model.PageModel;
using System.Web.Script.Serialization;

namespace RFrameGenerate.BLL
{
    public class MerchantManage
    {
        public static void Test()
        {
            //using (var query = Factory.CreateT_BAS_Merchants())
            //{
            //    //query.Add(new T_BAS_Merchants()
            //    //{
            //    //    MerchantGuid = Guid.NewGuid(),
            //    //    WeChatGuid = null,
            //    //    UserID = "fenxiao10001",
            //    //    Password = MD5Crypto.MD5("123456"),
            //    //    StoreTitle = "六六分销",
            //    //    StoreSubtitle = "分销俱乐部",
            //    //});
            //}

        }

        public static List<T_BAS_Merchants> GetMerchList(Guid agentGuid)
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                return query.GetList(c => c.AgentGuid == agentGuid);
            }
        }

        public static Result SetEnabel(Guid id, bool enable)
        {

            using (var query = Factory.CreateT_BAS_Merchants())
            {
                query.Update(a => new object[] { a.IsEnable == enable }, b => b.MerchantGuid == id);
                return new Result(true);
            }
        }

        public static string GetPriceLable()
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                return
                    query.GetFirstData(c => c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid)
                        .PriceLable;
            }
        }

        public static int GetPageProductNum()
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                var para = query.GetFirstData(c => c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
                if (para != null)
                    return para.HomePageProductNum ?? 4;
                else
                    return 4;
            }
        }

        public static string GetDomain()
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                return query.GetFirstData(c => c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid).StoreUrl;
            }
        }

        public static List<T_BAS_Merchants> GetMerchantPageList(GridModel grid, Guid? guid, string userid, string title, string type)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_Merchants(tran);
                Expression<Func<T_BAS_Merchants, bool>> exp = a => a.UserID == userid && a.StoreTitle.SqlLike(title);
                if (guid != Guid.Empty)
                {
                    if (Common.CurrentUser.GetLoginType() == DictionaryConst.LoginType.HeadOffice)
                    {
                        if (guid != null)
                            exp = exp.AndAlso(a => a.AgentGuid == guid);
                        else
                            exp = exp.AndAlso(a => a.AgentGuid == Common.CurrentUser.GetCurrUserGuid());
                    }
                    else
                    {
                        exp = exp.AndAlso(a => a.AgentGuid == Common.CurrentUser.GetCurrUserGuid());
                    }
                }
                else
                {
                    if (Common.CurrentUser.GetLoginType() == DictionaryConst.LoginType.HeadOffice)
                    {
                        var queryAgent = Factory.CreateT_BAS_Agents(tran);
                        var agentlist = queryAgent.GetList(a => a.ParentAgentGuid == CurrentUser.GetCurrUserGuid());
                        var guidlist = agentlist.Select(a => (Guid?)a.AgentGuid).ToList();
                        guidlist.Add(CurrentUser.GetCurrUserGuid());
                        var guids = guidlist.ToArray();
                        exp = exp.AndAlso(a => a.AgentGuid.SqlIn(guids));
                    }
                    else
                    {
                        exp = exp.AndAlso(a => a.AgentGuid == Common.CurrentUser.GetCurrUserGuid());
                    }
                }


                if (type == "0")
                {
                    exp = exp.AndAlso(a => a.UserType == 1 || a.UserType == 2 || a.UserType == 4 || a.UserType == 5);
                }

                if (!string.IsNullOrEmpty(type) && type != "0")
                {
                    var t = int.Parse(type);
                    exp = exp.AndAlso(a => a.UserType == t);
                }

                return query.GetPageList(grid, exp, true, b => b.CreateDate, DAL.Enums.OrderMethods.DESC);
            }
        }

        public static Result IsValid(string loginName, string password, string oldPwd, out T_BAS_Merchants user)
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                user = query.GetFirstData(a => a.UserID == loginName);
                if (user == null)
                    return new Result(false, "不存在用户:" + loginName);

                if (user.Password == password)
                {
                    if (user.CreateDate <= DateTime.Now && DateTime.Now <= user.ExpireDate)
                    {
                        return new Result(true);
                    }
                    else
                    {
                        return new Result(false, "账号已过期");
                    }
                }
                else
                {
                    return new Result(false, "密码不正确");
                }
            }
        }

        public static Result IsKeyValid(string loginName, string key, out T_BAS_Merchants user)
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                user = query.GetFirstData(a => a.UserID == loginName);
                if (user == null)
                    return new Result(false, "不存在用户:" + loginName);
                if (user.Password == key)
                {
                    if (user.CreateDate <= DateTime.Now && DateTime.Now <= user.ExpireDate)
                    {
                        return new Result(true);
                    }
                    else
                    {
                        return new Result(false, "账号已过期");
                    }
                }
                else
                    return new Result(false, "密码不正确");
            }
        }

        public static T_BAS_Merchants GetMerchant(Guid merchantguid)
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                return query.GetFirstData(a => a.MerchantGuid == merchantguid, isFilterMerchant: false);
            }
        }
        public static T_BAS_Merchants GetMerchantByAppID(string appid)
        {
            using (SqlRTransaction tran = new SqlRTransaction())
            {
                var queryMem = Factory.CreateT_WX_WeChat(tran);
                var wechat = queryMem.GetFirstData(string.Format(" appid = '{0}'", appid), " SCreateDate", OrderMethods.DESC);
                var queryMer = Factory.CreateT_BAS_Merchants(tran);
                return queryMer.GetFirstData(a => a.WeChatGuid == wechat.WeChatGuid);
            }
        }
        public static T_BAS_Merchants GetMerchantByAppID(Guid wechatGuid)
        {
            using (SqlRTransaction tran = new SqlRTransaction())
            {
                var queryMer = Factory.CreateT_BAS_Merchants(tran);
                return queryMer.GetFirstData(a => a.WeChatGuid == wechatGuid);
            }
        }
        public static T_BAS_Merchants GetMerchantByOriginalID(string wechatOriginalID, out string appid)
        {
            using (SqlRTransaction tran = new SqlRTransaction())
            {
                var queryMem = Factory.CreateT_WX_WeChat(tran);
                var wechat = queryMem.GetFirstData(a => a.user_name == wechatOriginalID);
                appid = wechat.appid;
                var queryMer = Factory.CreateT_BAS_Merchants(tran);
                return queryMer.GetFirstData(a => a.WeChatGuid == wechat.WeChatGuid);
            }
        }
        public static T_BAS_Merchants GetMerchantByUserID(string userID)
        {
            using (SqlRTransaction tran = new SqlRTransaction())
            {
                var queryMer = Factory.CreateT_BAS_Merchants(tran);
                return queryMer.GetFirstData(a => a.UserID == userID, isFilterMerchant: false);
            }
        }

        public static T_BAS_Merchants GetEntity(Guid guid)
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                return query.GetFirstData(a => a.MerchantGuid == guid);
            }
        }


        public static List<T_BAS_Merchants> GetList()
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                return query.GetList(c => c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
            }
        }


        /// <summary>
        /// update store parameter
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static Result UpdateStorePar(T_BAS_Merchants entity)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_Merchants(tran);
                var merchmodel = query.GetFirstData(a => a.MerchantGuid == CurrentManage.MerchantGuid);

                tran.BeginTransaction();
                if (entity.HomePageProductNum == null) entity.HomePageProductNum = 4;
                query.Update(c => new object[]
                {
                    c.Address==entity.Address,
                    c.Area==entity.Area,
                    c.City==entity.City,
                    c.Country==entity.Country,
                    c.Province==entity.Province,
                    c.EMail==entity.EMail,
                    c.StoreTitle==entity.StoreTitle,
                    c.Telephone==entity.Telephone,
                    c.StoreLogo==entity.StoreLogo,
                    c.DistributionBackgroundImgae==entity.DistributionBackgroundImgae,
                    c.BusinessIntroduceImage==entity.BusinessIntroduceImage,
                    c.Zip==entity.Zip,
                    c.PriceLable==entity.PriceLable,
                    c.CustomerName==entity.CustomerName,
                    c.CustomerTelephone==entity.CustomerTelephone,
                    c.HomePageProductNum==entity.HomePageProductNum,
                    c.Contact==entity.Contact,
                    c.StoreDescription == entity.StoreDescription,
                    c.StoreUrl==entity.StoreUrl
                }, a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);

                if (merchmodel.DistributionBackgroundImgae != entity.DistributionBackgroundImgae)
                {
                    SqlHelper.ExecuteNonQuery("update [T_BAS_DistributionProp] set DistributionQRCode='' where SMerchantGuid='" + CurrentManage.MerchantGuid + "'", tran);
                }
                tran.Commit();
            }
            return new Result(true);
        }

        /// <summary>
        /// 开通商家
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="merchantGuid"></param>
        /// <returns></returns>
        public static Result AddMerchantsPar(T_BAS_Merchants entity, int year, string packGuid, int version)
        {
            decimal DepositsAmount = 0;
            decimal CumulativeAmount = 0;
            decimal Balance = 0;
            string description = "";
            entity.UserType = version;
            using (var tran = new SqlRTransaction())
            {
                tran.BeginTransaction();

                var query = Factory.CreateT_BAS_Merchants(tran);
                var queryLevel = Factory.CreateT_BAS_Level(tran);
                var queryAgent = Factory.CreateT_BAS_Agents(tran);
                var queryOpen = Factory.CreateT_BAS_OpenMerchantRrecords(tran);
                var queryShip = Factory.CreateT_BAS_AgentsFlagship(tran);
                var queryPack = Factory.CreateT_BAS_FlagshipPack(tran);
                decimal amount = 0M;

                var agent = queryAgent.GetFirstData(a => a.AgentGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
                if (agent == null) return new Result(false, "找不到该代理商！");
                var level = queryLevel.GetFirstData(a => a.LevelGuid == agent.LevelGuid);
                if (level == null) return new Result(false, "找不到该代理商级别！");
                switch (version)
                {
                    case DictionaryConst.Versionb.Syb:
                        amount = year * level.SybVersion.Value;
                        break;
                    case DictionaryConst.Versionb.Flagship:
                        amount = year * level.FlagshipVersion.Value;
                        break;
                }
                if (query.IsExist(a => a.UserID == entity.UserID) != true)
                {
                    if (RFrameGenerate.Common.CurrentManage.LoginType == DictionaryConst.LoginType.Agent)
                    {
                        if (DateTime.Now > agent.ExpireData)
                        {
                            return new Result(false, "您的账号已过期");
                        }
                        //预存款
                        DepositsAmount = agent.DepositsAmount;
                        //累计消费
                        CumulativeAmount = agent.CumulativeAmount + amount;
                        //余额
                        Balance = DepositsAmount - CumulativeAmount;

                        if (Balance < 0)
                            return new Result(false, "余额不足,请先充值.");

                    }
                    queryAgent.Update(a => new object[] 
                    {
                        a.CumulativeAmount==CumulativeAmount
                    }, b => b.AgentGuid == agent.AgentGuid);

                    query.Add(entity);

                    if (entity.UserType == 2)
                    {

                        if (RFrameGenerate.Common.CurrentManage.LoginType == DictionaryConst.LoginType.HeadOffice)
                        {
                            var model_pack = queryPack.GetFirstData(a => a.FlagshipPackGuid == new Guid(packGuid), false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                            if (model_pack == null) return new Result(false, "找不到该套餐！");
                            var num = model_pack.MerchantNum;
                            queryShip.Add(new T_BAS_AgentsFlagship
                            {
                                AgentsFlagshipGuid = Guid.NewGuid(),
                                FlagshipPackGuid = new Guid(packGuid),
                                MerchantGuid = entity.MerchantGuid,
                                OpenMerchanMaxNum = num,
                                OpenMerchandNum = 0
                            });
                        }
                        if (RFrameGenerate.Common.CurrentManage.LoginType == DictionaryConst.LoginType.Agent)
                        {
                            queryShip.Add(new T_BAS_AgentsFlagship
                            {
                                AgentsFlagshipGuid = Guid.NewGuid(),
                                FlagshipPackGuid = new Guid(packGuid),
                                MerchantGuid = entity.MerchantGuid
                            });
                        }
                    }
                    //备注
                    description = version == DictionaryConst.Versionb.Syb ? "开通创业版" : "开通旗舰版";
                    queryOpen.Add(new T_BAS_OpenMerchantRrecords()
                    {
                        OpenMerchantRrecordGuid = Guid.NewGuid(),
                        AgentGuid = agent.AgentGuid,
                        Amount = amount,

                        AvailableBalance = Balance,
                        Remark = description,
                        OpenDate = DateTime.Now,
                        PayType = DictionaryConst.PayType.FirstOpened,
                        OpenType = version,
                        OpenYear = year,
                        MerchantGuid = entity.MerchantGuid
                    });
                    tran.Commit();
                    query.Dispose();
                    queryAgent.Dispose();
                    queryLevel.Dispose();
                    queryOpen.Dispose();
                    queryShip.Dispose();

                    return new Result(true);
                }
                else
                {
                    return new Result(false, entity.UserID + "已存在");
                }
            }
        }


        /// <summary>
        /// 添加测试商家
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static Result AddMerchantTemp(T_BAS_Merchants entity)
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                try
                {
                    query.Add(entity);
                    return new Result(true);
                }
                catch (Exception ex)
                {
                    return new Result(false, ex.Message);
                }
            }
        }

        /// <summary>
        /// 升级旗舰版 原算法（结算当前版本余额）
        /// </summary>
        /// <param name="merchantGuid"></param>
        /// <param name="userType"></param>
        /// <param name="year"></param>
        /// <param name="packGuid"></param>
        /// <returns></returns>
        public static Result EditMerchantsPar(Guid merchantGuid, int userType, int year, string packGuid)
        {

            using (var tran = new SqlRTransaction())
            {
                tran.BeginTransaction();
                var query = Factory.CreateT_BAS_Merchants(tran);
                var queryLevel = Factory.CreateT_BAS_Level(tran);
                var queryAgent = Factory.CreateT_BAS_Agents(tran);
                var queryShip = Factory.CreateT_BAS_AgentsFlagship(tran);
                var queryRecords = Factory.CreateT_BAS_OpenMerchantRrecords(tran);
                var queryPack = Factory.CreateT_BAS_FlagshipPack(tran);
                decimal flagshipVersion = 0M;
                decimal sybVersion = 0M;
                decimal DepositsAmount = 0;
                decimal CumulativeAmount = 0;
                decimal Balance = 0;
                decimal Pay = 0;
                string description = "";
                var merchant = query.GetFirstData(a => a.MerchantGuid == merchantGuid);
                if (merchant == null) return new Result(false, "该商家不存在！");

                var agent = queryAgent.GetFirstData(a => a.AgentGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
                if (agent == null) return new Result(false, "找不到该代理商！");
                var level = queryLevel.GetFirstData(a => a.LevelGuid == agent.LevelGuid);
                if (level == null) return new Result(false, "找不到该代理商级别！");
                var model_flagshipPack = queryPack.GetFirstData(a => a.FlagshipPackGuid == new Guid(packGuid), false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                if (model_flagshipPack == null) return new Result(false, "找不到该旗舰版套餐！");


                //创业版开通年数
                int years = YearsDiff(merchant.CreateDate.Value, merchant.ExpireDate.Value);
                //使用月数
                int months = GetMonth(merchant.CreateDate.Value, DateTime.Now);
                //旗舰版金额
                flagshipVersion = year * level.FlagshipVersion.Value;

                //创业版金额
                sybVersion = years * level.SybVersion.Value;

                //预存款
                DepositsAmount = agent.DepositsAmount + sybVersion - level.SybVersion.Value / 12 * months;
                //原累计消费
                CumulativeAmount = agent.CumulativeAmount;

                //消费
                Pay = flagshipVersion + level.SybVersion.Value / 12 * months - sybVersion;

                if (RFrameGenerate.Common.CurrentManage.LoginType == DictionaryConst.LoginType.Agent)
                {

                    if (userType != 2)
                    {
                        return new Result(false, "您的账号不能升级！");
                    }
                    if (DateTime.Now > agent.ExpireData)
                    {
                        return new Result(false, "您的账号已过期");
                    }
                    if (DepositsAmount - CumulativeAmount < (year * level.FlagshipVersion.Value))
                    {
                        return new Result(false, "余额不足,请先充值.");
                    }

                }
                //现累计消费
                CumulativeAmount = CumulativeAmount + Pay;
                //余额
                Balance = DepositsAmount - CumulativeAmount;

                description = "升级旗舰版";

                queryAgent.Update(a => new object[] 
                {
                    a.CumulativeAmount==CumulativeAmount
                }, b => b.AgentGuid == agent.AgentGuid);

                var model = query.GetFirstData(a => a.MerchantGuid == merchantGuid);
                model.UserType = userType;
                model.CreateDate = DateTime.Now;
                model.ExpireDate = DateTime.Now.AddYears(year);
                query.Update(model);

                //更新旗舰版开通代理上限
                var num = model_flagshipPack.MerchantNum == null ? 0 : model_flagshipPack.MerchantNum;

                queryShip.Add(new T_BAS_AgentsFlagship
                {
                    AgentsFlagshipGuid = Guid.NewGuid(),
                    FlagshipPackGuid = new Guid(packGuid),
                    MerchantGuid = merchantGuid,
                    OpenMerchanMaxNum = num,
                    OpenMerchandNum = 0
                });

                queryRecords.Add(new T_BAS_OpenMerchantRrecords
                {
                    OpenMerchantRrecordGuid = Guid.NewGuid(),
                    AgentGuid = merchant.AgentGuid,
                    MerchantGuid = merchant.MerchantGuid,
                    OpenDate = DateTime.Now,
                    OpenType = userType,
                    PayType = DictionaryConst.PayType.Upgrade,
                    OpenYear = year,
                    Amount = Pay,
                    AvailableBalance = Balance,
                    Remark = description

                });
                tran.Commit();
                query.Dispose();
                queryAgent.Dispose();
                queryLevel.Dispose();
                queryShip.Dispose();
                queryRecords.Dispose();
                return new Result(true);
            }
        }

        /// <summary>
        /// 升级旗舰版 新算法（补版本差价）
        /// </summary>
        /// <param name="merchantGuid"></param>
        /// <param name="userType"></param>
        /// <param name="year"></param>
        /// <param name="packGuid"></param>
        /// <returns></returns>
        public static Result EditMerchantsPar(Guid merchantGuid, int userType, string packGuid)
        {

            using (var tran = new SqlRTransaction())
            {
                tran.BeginTransaction();
                var query = Factory.CreateT_BAS_Merchants(tran);
                var queryLevel = Factory.CreateT_BAS_Level(tran);
                var queryAgent = Factory.CreateT_BAS_Agents(tran);
                var queryShip = Factory.CreateT_BAS_AgentsFlagship(tran);
                var queryRecords = Factory.CreateT_BAS_OpenMerchantRrecords(tran);
                var queryPack = Factory.CreateT_BAS_FlagshipPack(tran);
                decimal flagshipVersion = 0M;
                decimal sybVersion = 0M;
                decimal DepositsAmount = 0;
                decimal CumulativeAmount = 0;
                decimal Balance = 0;
                decimal Pay = 0;
                string description = "";
                var merchant = query.GetFirstData(a => a.MerchantGuid == merchantGuid);
                if (merchant == null) return new Result(false, "该商家不存在！");
                var agent = queryAgent.GetFirstData(a => a.AgentGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
                if (agent == null) return new Result(false, "找不到该代理商！");
                var level = queryLevel.GetFirstData(a => a.LevelGuid == agent.LevelGuid);
                if (level == null) return new Result(false, "找不到该代理商级别！");
                var model_flagshipPack = queryPack.GetFirstData(a => a.FlagshipPackGuid == new Guid(packGuid), false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                if (model_flagshipPack == null) return new Result(false, "找不到该旗舰版套餐！");
                var records = queryRecords.GetFirstData(a => a.MerchantGuid == merchantGuid && a.OpenType == DictionaryConst.Versionb.Syb && a.AgentGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
                int year = merchant.ExpireDate.Value.Year - merchant.CreateDate.Value.Year;
                //升级版本类型
                merchant.UserType = userType;

                description = "升级旗舰版";
                //旗舰版开通代理上限
                var num = model_flagshipPack.MerchantNum == null ? 0 : model_flagshipPack.MerchantNum;
                //旗舰版金额
                flagshipVersion = year * level.FlagshipVersion.Value;

                //创业版金额
                if (records == null)
                {
                    sybVersion = year * level.SybVersion.Value;
                }
                else
                {
                    sybVersion = records.Amount.Value;
                }
                //预存款
                DepositsAmount = agent.DepositsAmount;
                //原累计消费
                CumulativeAmount = agent.CumulativeAmount;

                //消费
                Pay = flagshipVersion - sybVersion;

                //现累计消费
                CumulativeAmount += Pay;

                if (RFrameGenerate.Common.CurrentManage.LoginType == DictionaryConst.LoginType.Agent)
                {

                    if (userType != 2)
                    {
                        return new Result(false, "您的账号不能升级！");
                    }
                    if (DateTime.Now > agent.ExpireData)
                    {
                        return new Result(false, "您的账号已过期");
                    }
                    if (DepositsAmount - CumulativeAmount < 0)
                    {
                        return new Result(false, "余额不足,请先充值.");
                    }
                    //余额
                    Balance = DepositsAmount - CumulativeAmount;
                }
                //更新代理累计消费
                queryAgent.Update(a => new object[] 
                {
                    a.CumulativeAmount==CumulativeAmount
                }, b => b.AgentGuid == agent.AgentGuid);

                //更新商家
                query.Update(merchant);

                queryShip.Add(new T_BAS_AgentsFlagship
                {
                    AgentsFlagshipGuid = Guid.NewGuid(),
                    FlagshipPackGuid = new Guid(packGuid),
                    MerchantGuid = merchantGuid,
                    OpenMerchanMaxNum = num,
                    OpenMerchandNum = 0
                });

                queryRecords.Add(new T_BAS_OpenMerchantRrecords
                {
                    OpenMerchantRrecordGuid = Guid.NewGuid(),
                    AgentGuid = merchant.AgentGuid,
                    MerchantGuid = merchant.MerchantGuid,
                    OpenDate = DateTime.Now,
                    OpenType = userType,
                    PayType = DictionaryConst.PayType.Upgrade,
                    OpenYear = year,
                    Amount = Pay,
                    AvailableBalance = Balance,
                    Remark = description
                });
                tran.Commit();
                query.Dispose();
                queryAgent.Dispose();
                queryLevel.Dispose();
                queryShip.Dispose();
                queryRecords.Dispose();
                return new Result(true);
            }
        }


        /// <summary>
        /// 修改：专用测试版升级到旗舰/创业版  Bing 20160114  
        /// </summary>
        /// <param name="merchantGuid"></param>
        /// <param name="userType"></param>
        /// <param name="year"></param>
        /// <param name="packGuid"></param>
        /// <returns></returns>
        public static Result EditMerchantsParTempTest(Guid merchantGuid, int userType, string packGuid, int years)
        {

            decimal DepositsAmount = 0;
            decimal CumulativeAmount = 0;
            decimal Balance = 0;
            string description = "";
            //entity.UserType = version;
            using (var tran = new SqlRTransaction())
            {
                tran.BeginTransaction();

                var query = Factory.CreateT_BAS_Merchants(tran);
                var queryLevel = Factory.CreateT_BAS_Level(tran);
                var queryAgent = Factory.CreateT_BAS_Agents(tran);
                var queryOpen = Factory.CreateT_BAS_OpenMerchantRrecords(tran);
                var queryShip = Factory.CreateT_BAS_AgentsFlagship(tran);
                var queryPack = Factory.CreateT_BAS_FlagshipPack(tran);
                decimal amount = 0M;

                var agent = queryAgent.GetFirstData(a => a.AgentGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid());
                if (agent == null) return new Result(false, "找不到该代理商！");
                var level = queryLevel.GetFirstData(a => a.LevelGuid == agent.LevelGuid);
                if (level == null) return new Result(false, "找不到该代理商级别！");

                switch (userType)//升级类型
                {
                    case DictionaryConst.Versionb.Syb:
                        amount = years * level.SybVersion.Value;
                        break;
                    case DictionaryConst.Versionb.Flagship:
                        amount = years * level.FlagshipVersion.Value;
                        break;
                }

                //获取商家
                var entity = query.GetDataByGuid(merchantGuid);
                entity.UserType = userType;

                if (true/*query.IsExist(a => a.UserID == entity.UserID) != true*/)
                {
                    if (RFrameGenerate.Common.CurrentManage.LoginType == DictionaryConst.LoginType.Agent)
                    {
                        if (DateTime.Now > agent.ExpireData)
                        {
                            return new Result(false, "您的账号已过期");
                        }
                        //预存款
                        DepositsAmount = agent.DepositsAmount;
                        //累计消费
                        CumulativeAmount = agent.CumulativeAmount + amount;
                        //余额
                        Balance = DepositsAmount - CumulativeAmount;

                        if (Balance < 0)
                            return new Result(false, "余额不足,请先充值.");

                    }
                    queryAgent.Update(a => new object[] 
                    {
                        a.CumulativeAmount==CumulativeAmount
                    }, b => b.AgentGuid == agent.AgentGuid);

                    //query.Add(entity);
                    //修改商家类型、过期时间
                    query.Update(c => new object[]
                    { 
                        c.UserType==entity.UserType ,
                        c.ExpireDate==entity.ExpireDate.Value.AddYears(years)
                    }, c => c.MerchantGuid == entity.MerchantGuid);


                    if (entity.UserType == 2)
                    {

                        if (RFrameGenerate.Common.CurrentManage.LoginType == DictionaryConst.LoginType.HeadOffice)
                        {
                            var model_pack = queryPack.GetFirstData(a => a.FlagshipPackGuid == new Guid(packGuid), false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                            if (model_pack == null) return new Result(false, "找不到该套餐！");
                            var num = model_pack.MerchantNum;
                            queryShip.Add(new T_BAS_AgentsFlagship
                            {
                                AgentsFlagshipGuid = Guid.NewGuid(),
                                FlagshipPackGuid = new Guid(packGuid),
                                MerchantGuid = entity.MerchantGuid,
                                OpenMerchanMaxNum = num,
                                OpenMerchandNum = 0
                            });
                        }
                        if (RFrameGenerate.Common.CurrentManage.LoginType == DictionaryConst.LoginType.Agent)
                        {
                            queryShip.Add(new T_BAS_AgentsFlagship
                            {
                                AgentsFlagshipGuid = Guid.NewGuid(),
                                FlagshipPackGuid = new Guid(packGuid),
                                MerchantGuid = entity.MerchantGuid
                            });
                        }
                    }
                    //备注
                    description = userType == DictionaryConst.Versionb.Syb ? "开通创业版" : "开通旗舰版";
                    queryOpen.Add(new T_BAS_OpenMerchantRrecords()
                    {
                        OpenMerchantRrecordGuid = Guid.NewGuid(),
                        AgentGuid = agent.AgentGuid,
                        Amount = amount,

                        AvailableBalance = Balance,
                        Remark = description,
                        OpenDate = DateTime.Now,
                        PayType = DictionaryConst.PayType.FirstOpened,
                        OpenType = userType,
                        OpenYear = years,
                        MerchantGuid = entity.MerchantGuid
                    });
                    tran.Commit();
                    query.Dispose();
                    queryAgent.Dispose();
                    queryLevel.Dispose();
                    queryOpen.Dispose();
                    queryShip.Dispose();

                    return new Result(true);
                }
                else
                {
                    return new Result(false, entity.UserID + "已存在");
                }
            }



        }






        /// <summary>
        /// 计算相差月份
        /// </summary>
        /// <param name="dateTime1">开通时间</param>
        /// <param name="dateTime2">当前时间</param>
        /// <returns></returns>
        private static int GetMonth(DateTime dateTime1, DateTime dateTime2)
        {
            int month = 0;
            int days = DaysDiff(dateTime1, dateTime2);

            if ((days % 30) != 0)
            {
                month = days / 30 + 1;
            }
            else
            {
                month = days / 30;
            }
            return month;
        }
        /// <summary>
        /// 时间差
        /// </summary>
        /// <param name="DateTime1"></param>
        /// <param name="DateTime2"></param>
        /// <returns></returns>
        public static int DaysDiff(DateTime DateTime1, DateTime DateTime2)
        {
            int dateDiff = 0;
            try
            {
                TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                TimeSpan ts = ts1.Subtract(ts2).Duration();
                dateDiff = int.Parse(ts.Days.ToString());
            }
            catch
            {

            }
            return dateDiff;
        }
        /// <summary>
        /// 计算相差年份
        /// </summary>
        /// <param name="DateTime1"></param>
        /// <param name="DateTime2"></param>
        /// <returns></returns>
        public static int YearsDiff(DateTime DateTime1, DateTime DateTime2)
        {
            int yearsDiff = 0;
            try
            {
                yearsDiff = DateTime2.Year - DateTime1.Year;
            }
            catch
            {

            }
            return yearsDiff;
        }
        public static Result ChangePassword(Guid id, string password)
        {
            try
            {
                using (var query = Factory.CreateT_BAS_Merchants())
                {
                    query.Update(a => new object[]
                {
                    a.Password== RFrameGenerate.Common.Utils.Md5( password)
                }, b => b.MerchantGuid == id);
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        public static Result ChangePassword(string userid, string password)
        {
            try
            {
                using (var query = Factory.CreateT_BAS_Merchants())
                {
                    var user = query.GetFirstData(a => a.UserID == userid);
                    if (user == null)
                        return new Result(false, "用户不存在");
                    query.Update(a => new object[]
                {
                    a.Password== RFrameGenerate.Common.Utils.Md5( password)
                }, b => b.UserID == userid);
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        public static Result UpdateSystemSetting(bool storeState, string closeReason)
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                query.Update(c => new object[]
                {
                    c.CloseReason==closeReason,
                    c.StoreState==storeState
                }, a => a.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);
            }
            return new Result(true);
        }
        public static PT_BAS_Distribute_GetTotal GetDistributeTotal()
        {
            using (var query = Factory.CreateProcedure())
            {
                return query.GetDistributeTotal();
            }
        }

        public static string GetStoreName()
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                return query.GetFirstData(c => c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid).StoreTitle;
            }
        }

        public static string GetBackgroundImgae()
        {
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                return query.GetFirstData(c => c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid)
                        .DistributionBackgroundImgae;
            }
        }

        public static string GetStoreTitle(Guid guid)
        {
            string storeTitle = "";
            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 == guid);
                if (dis == null) return "";
                var user = querymem.GetFirstData(a => a.MemberGuid == dis.MemberGuid);
                if (user == null) return "";
                storeTitle = string.IsNullOrEmpty(dis.StoreTitle) ? user.MemberNickName + "的小店" : dis.StoreTitle;
            }
            return storeTitle;
        }

        public static string GetStoreTitleNotFilter(Guid guid)
        {
            string storeTitle = "";
            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 == guid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                if (dis == null) return "";
                var user = querymem.GetFirstData(a => a.MemberGuid == dis.MemberGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                if (user == null) return "";
                storeTitle = string.IsNullOrEmpty(dis.StoreTitle) ? user.MemberNickName + "的小店" : dis.StoreTitle;
            }
            return storeTitle;
        }

        public static List<T_BAS_FlagshipGroupWithParaLite> GetPageList(GridModel gridModel, string groupName)
        {
            using (var tran = new RFramework.SQLServer.SqlRTransaction())
            {
                var queryFlagShip = Factory.CreateT_BAS_FlagshipGroupWithParaLite(tran);
                var flagShipResult = queryFlagShip.GetPageList(gridModel, c => c.GroupName.SqlLike(groupName), true, p => p.Sort);
                if (flagShipResult != null)
                {
                    return flagShipResult;
                }
                return new List<T_BAS_FlagshipGroupWithParaLite>();
            }
        }

        public static Result DeleteEntity(Guid entityGuid)
        {
            if (entityGuid == Guid.Empty) return new Result(false, "没有数据删除！");
            using (SqlRTransaction tran = new SqlRTransaction())
            {
                try
                {
                    tran.BeginTransaction();
                    var queryAgentsFlagship = Factory.CreateT_BAS_AgentsFlagship(tran);
                    var queryAgentsProDis = Factory.CreateT_BAS_AgentProductDiscount(tran);
                    var queryAgentDis = Factory.CreateT_BAS_AgentProductDiscountDetail(tran);
                    var query = Factory.CreateT_BAS_FlagshipGroup(tran);
                    if (queryAgentsFlagship.IsExist(c => c.FlagshipGroupGuid == entityGuid, false))
                    {
                        return new Result(false, "此代理分组下存在代理商,不能删除");
                    }
                    if (queryAgentDis.IsExist(c => c.FlagshipGroupGuid == entityGuid, false))
                    {
                        return new Result(false, "此代理分组已在代理分组商品中,不能删除");
                    }

                    query.Delete(a => a.FlagshipGroupGuid == entityGuid);
                    query.Delete(c => c.FlagshipGroupGuid == entityGuid);
                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return new Result(false, ex.Message);
                }
            }
        }


        public static Result SaveChangeEntity(T_BAS_FlagshipGroup entity, string tempArr)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    tran.BeginTransaction();
                    var query = Factory.CreateT_BAS_FlagshipPara(tran);
                    var query_Mer = Factory.CreateT_BAS_Merchants(tran);
                    var query_Agen = Factory.CreateT_BAS_AgentsFlagship(tran);
                    var queryFlagShip = Factory.CreateT_BAS_FlagshipGroup(tran);
                    var query_ProductDiscount = Factory.CreateT_BAS_AgentProductDiscount(tran);
                    var topGuid = GetTopestGuidByCurrentGuid(RFrameGenerate.Common.CurrentManage.MerchantGuid);
                    var agentFlagShipResult = query_Agen.GetFirstData(a => a.MerchantGuid == topGuid, false, null, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                    if (agentFlagShipResult != null)
                    {
                        var isExit = queryFlagShip.GetFirstData(a => a.FlagshipGroupGuid == entity.FlagshipGroupGuid, false, null, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                        entity.AgentsFlagshipGuid = agentFlagShipResult.AgentsFlagshipGuid;
                        if (isExit != null)
                        {
                            if (entity.FlagshipParaGuid != isExit.FlagshipParaGuid)
                            {
                                var oldEntity = query.GetFirstData(c => c.FlagshipParaGuid == isExit.FlagshipParaGuid);
                                var newEntity = query.GetFirstData(c => c.FlagshipParaGuid == entity.FlagshipParaGuid);
                                if (newEntity.UserWeChatType != oldEntity.UserWeChatType)
                                {
                                    Guid? currWeChatGuid = null;
                                    if (newEntity.UserWeChatType == AgentRuleConst.UserWeChatType.总部)
                                    {
                                        currWeChatGuid = query_Mer.GetFirstData(c => c.MerchantGuid == CurrentManage.MerchantGuid, isFilterMerchant: false).WeChatGuid;
                                    }
                                    var listAgen = query_Agen.GetList(c => c.FlagshipGroupGuid == isExit.FlagshipGroupGuid, isFilterMerchant: false);
                                    if (listAgen != null && listAgen.Count > 0)
                                    {
                                        query_Mer.Update(c => new object[]{
                                c.WeChatGuid==currWeChatGuid
                               }, c => c.MerchantGuid.SqlIn(listAgen.Select(m => m.MerchantGuid.Value).ToArray()), isFilterMerchant: false);
                                    }

                                }
                            }
                            queryFlagShip.Update(entity);
                        }
                        else
                        {
                            var isHas = queryFlagShip.GetCount(a => a.GroupName == entity.GroupName, false, true);
                            if (isHas > 0)
                            {
                                tran.Rollback();
                                return new Result(false, "当前分组名称已有记录，请更改分组名称");
                            }
                            queryFlagShip.Add(entity);
                        }

                        if (!string.IsNullOrWhiteSpace(tempArr))
                        {
                            var arr = new JavaScriptSerializer().Deserialize<decimal[]>(tempArr);
                            if (arr.Length > 0)
                            {
                                List<T_BAS_AgentProductDiscount> listPd = new List<T_BAS_AgentProductDiscount>();
                                for (int i = 0, j = 0; i < arr.Length; i++, j++)
                                {
                                    listPd.Add(new T_BAS_AgentProductDiscount()
                                    {
                                        AgentProductDiscountGuid = Guid.NewGuid(),
                                        FlagshipGroupGuid = entity.FlagshipGroupGuid,
                                        PaymentType = entity.AgentJoinType,
                                        PaymentMoney = arr[i],
                                        Discount = arr[i + 1],
                                        Sort = j,
                                        EntityState = EntityStates.ToBeAdd
                                    });
                                    i++;
                                }
                                query_ProductDiscount.Delete(c => c.FlagshipGroupGuid == entity.FlagshipGroupGuid, isFilterMerchant: false);
                                query_ProductDiscount.AddList(listPd);
                            }
                        }

                        tran.Commit();
                        return new Result(true);
                    }



                    tran.Commit();
                    return new Result(false, "保存失败，旗舰版不存在");

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

        public static List<T_BAS_FlagshipGroup> GetFlagShipGroupList()
        {
            using (var tran = new RFramework.SQLServer.SqlRTransaction())
            {
                var queryFlagShip = Factory.CreateT_BAS_FlagshipGroup(tran);
                var flagShipResult = queryFlagShip.GetList(null, true, p => p.Sort);
                if (flagShipResult != null)
                {
                    return flagShipResult;
                }
                return new List<T_BAS_FlagshipGroup>();
            }
        }



        public static Result SaveFlagShipGroupSelf(T_BAS_Merchants entity, string userid, Guid agentGroupGuid, Guid? AgentProductDiscountGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    tran.BeginTransaction();

                    var queryMerchant = Factory.CreateT_BAS_Merchants(tran);
                    var queryAgentsFlagship = Factory.CreateT_BAS_AgentsFlagship(tran);
                    var queryProductCategory = Factory.CreateT_BAS_ProductCategorys(tran);
                    var queryProduct = Factory.CreateT_BAS_Products(tran);
                    var queryProductType = Factory.CreateT_BAS_ProductType(tran);
                    var queryProductSKU = Factory.CreateT_BAS_ProductSKU(tran);
                    var queryProdure = Factory.CreateProcedure(tran);
                    var queryFactorageAccount = Factory.CreateT_BAS_FactorageAccount(tran);
                    var queryOpenAgentsApply = Factory.CreateT_BAS_OpenAgentsApply(tran);
                    var currMerchant = CurrentManage.MerchantGuid;


                    //得到顶级商家Guid
                    var topAgent = GetTopAgent(currMerchant);
                    if (topAgent == null) return new Result(false, "该代理总部不存在！");
                    var topMerchant = queryMerchant.GetDataByGuid(topAgent.MerchantGuid.Value, false);
                    if (topMerchant == null) return new Result(false, "该代理总部不存在！");

                    //获取当前代理规则
                    var rule = AgentRulesManage.GetUnifyFlagshipParaByGro(agentGroupGuid);

                    //可发展代理总数
                    var canDevelopCount = GetFlagPackMerchantNum();
                    //已发展代理总数
                    var haveDevelopCount = GetAgentCountFromTopToBottom(topAgent.MerchantGuid.Value);
                    if (haveDevelopCount >= canDevelopCount)
                    {
                        tran.Commit();
                        return new Result(false, "对不起，该旗舰版发展代理数超限");
                    }

                    //添加商家
                    var merchantIsext = queryMerchant.GetFirstData(a => a.UserID == entity.UserID);
                    if (merchantIsext != null)
                    {
                        tran.Commit();
                        return new Result(false, "对不起，该代理商ID已存在");
                    }
                    //var openAgentsApply = queryOpenAgentsApply.GetFirstData(a => a.UserID == userid, isFilterMerchant: false);
                    //if (openAgentsApply == null) return new Result(false, "对不起，该代理商申请不存在！");
                    ////更新代理商申请状态
                    //queryOpenAgentsApply.Update(a => new Object[] { a.ApplyState == DictionaryConst.ApplyState.Succeed }, a => a.OpenAgentsApplyGuid == openAgentsApply.OpenAgentsApplyGuid, isFilterMerchant: false);
                    //更新旗舰版商户开通数量
                    topAgent.OpenMerchandNum = topAgent.OpenMerchandNum == null ? 1 : topAgent.OpenMerchandNum.Value + 1;
                    queryAgentsFlagship.Update(a => new object[] { a.OpenMerchandNum == topAgent.OpenMerchandNum }, a => a.AgentsFlagshipGuid == topAgent.AgentsFlagshipGuid, false);

                    ////获取当前开通商家的上级代理
                    //var fatherFlagship = queryAgentsFlagship.GetFirstData(a => a.MerchantGuid == openAgentsApply.FatherMerchantGuid, isFilterMerchant: false);
                    //var flagshipGroupGuid = entity.AgentGuid;

                    //if (rule.UserWeChatType == AgentRuleConst.UserWeChatType.总部)
                    //{
                    //    entity.WeChatGuid = topMerchant.WeChatGuid;
                    //}

                    entity.MerchantGuid = Guid.NewGuid();
                    //entity.AgentGuid = fatherFlagship == null ? Guid.Empty : fatherFlagship.AgentsFlagshipGuid;
                    entity.AgentGuid = Guid.Empty;
                    entity.StoreState = true;
                    entity.CreateDate = DateTime.Now;
                    entity.ExpireDate = Convert.ToDateTime(entity.CreateDate).AddYears(3);
                    entity.IsEnable = true;
                    entity.UserType = DictionaryConst.Versionb.AgentFlagShip;
                    entity.Password = Utils.Md5(entity.Password);
                    entity.SMerchantGuid = entity.MerchantGuid;
                    entity.HomePageProductNum = 4;

                    entity.TotalDistributionOrders = 0;
                    entity.TotalDistributor = 0;
                    entity.MentionedAmount = 0;
                    entity.DistributionOrdersAmount = 0;
                    entity.CumulativeDistributionAmount = 0;
                    entity.IsCustomerServices = false;
                    entity.CustomerServicesGuid = null;
                    entity.CloseReason = "";

                    queryMerchant.Add(entity);

                    //添加旗舰版下级商户
                    T_BAS_AgentsFlagship agentFlagShip = new T_BAS_AgentsFlagship();
                    agentFlagShip.AgentsFlagshipGuid = Guid.NewGuid();
                    agentFlagShip.MerchantGuid = entity.MerchantGuid;
                    agentFlagShip.FlagshipGroupGuid = agentGroupGuid;
                    agentFlagShip.FatherMerchantGuid = currMerchant;
                    agentFlagShip.TopMerchantGuid = currMerchant;
                    agentFlagShip.SMerchantGuid = entity.MerchantGuid;
                    agentFlagShip.AgentProductDiscountGuid = AgentProductDiscountGuid;
                    if (AgentProductDiscountGuid != null)
                    {
                        var dis = AgentProductDisManage.GetAgentProDisByFk(AgentProductDiscountGuid);
                        agentFlagShip.PaymentType = dis.PaymentType;
                        agentFlagShip.PaymentMoney = dis.PaymentMoney;
                        agentFlagShip.Discount = dis.Discount;
                    }

                    queryAgentsFlagship.Add(agentFlagShip);

                    tran.Commit();
                    return new Result(true);


                    #region

                    List<T_BAS_Products> listProduct = new List<T_BAS_Products>();
                    List<T_BAS_ProductCategorys> addList = new List<T_BAS_ProductCategorys>();
                    var topType = queryProductCategory.GetList(a => a.MerchantGuid == topAgent.MerchantGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                    if (topType.Count > 0)
                    {
                        List<T_BAS_ProductCategorys> lstType = new List<T_BAS_ProductCategorys>();

                        lstType = topType.OrderBy(a => a.Levels).ThenBy(a => a.Sort).ToList();
                        foreach (var item in lstType)
                        {

                            var categoryguid = Guid.NewGuid();
                            var _entity = new T_BAS_ProductCategorys();
                            _entity.OriginalProductCategoryGuid = item.ProductCategoryGuid;
                            _entity.SMerchantGuid = CurrentManage.MerchantGuid;
                            _entity.CategoryCode = item.CategoryCode;
                            _entity.CategoryName = item.CategoryName;
                            _entity.Flag = item.Flag;
                            _entity.Levels = item.Levels;
                            _entity.MerchantGuid = agentFlagShip.MerchantGuid;
                            _entity.Sort = item.Sort;
                            _entity.Url = item.Url;
                            if (item.ParentGuid != null)
                            {
                                var model = addList.FirstOrDefault(a => a.OriginalProductCategoryGuid == item.ParentGuid && a.MerchantGuid == agentFlagShip.MerchantGuid);
                                if (model != null) _entity.ParentGuid = model.ProductCategoryGuid;
                            }
                            var model_category = addList.FirstOrDefault(a => a.MerchantGuid == agentFlagShip.MerchantGuid && a.CategoryName == item.CategoryName);
                            if (model_category == null)
                            {
                                _entity.ProductCategoryGuid = categoryguid;
                                queryProductCategory.Add(_entity);
                            }
                            else
                            {
                                _entity.ProductCategoryGuid = model_category.ProductCategoryGuid;
                                queryProductCategory.Update(_entity, false);
                            }
                            addList.Add(_entity);
                        }
                    }
                    var topProduct = queryProduct.GetList(a => a.MerchantGuid == topAgent.MerchantGuid && a.IsAgentsProduct == true, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                    if (topProduct.Count > 0)
                    {
                        string basePath = AppDomain.CurrentDomain.BaseDirectory + @"upload\qrcode\";
                        foreach (var subItem in topProduct)
                        {
                            //商品
                            T_BAS_Products product = new T_BAS_Products();
                            product.OriginalProductGuid = subItem.ProductGuid;
                            product.ProductGuid = Guid.NewGuid();
                            product.ProductTypeGuid = subItem.ProductTypeGuid;
                            product.MerchantGuid = agentFlagShip.MerchantGuid;
                            product.ProductName = subItem.ProductName;
                            product.ProductUrl = "http://" + entity.UserID + string.Format(".shop.{0}/wxshop/productinfo?productsguid={1}", CurrentManage.DomainWxRoot, product.ProductGuid);
                            var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + RadomCode.DigitalCode(3) + ".png";
                            if (Common.QrCodeHelper.GenerationQrCode(product.ProductUrl, "", basePath + fileName))
                            {
                                product.QRCodeUrl = "/upload/qrcode/" + fileName;
                            }
                            product.ProductCode = subItem.ProductCode;
                            product.MarketPrice = subItem.MarketPrice;
                            product.Price = subItem.Price;
                            product.MinPrice = subItem.MinPrice;
                            product.MaxPrice = subItem.MaxPrice;
                            product.IsAgentsProduct = false;
                            product.Inventory = subItem.Inventory;
                            product.Weight = subItem.Weight;
                            product.SalesVolume = subItem.SalesVolume;
                            product.BaseSalesVolume = subItem.BaseSalesVolume;
                            product.ProductImage = subItem.ProductImage;
                            product.ProductImage1 = subItem.ProductImage1;
                            product.ProductImage2 = subItem.ProductImage2;
                            product.ProductImage3 = subItem.ProductImage3;
                            product.ProductImage4 = subItem.ProductImage4;
                            product.ProductImage5 = subItem.ProductImage5;
                            product.FirstCommission = subItem.FirstCommission;
                            product.SecondCommission = subItem.SecondCommission;
                            product.ThirdCommission = subItem.ThirdCommission;
                            product.IsDefault = subItem.IsDefault;
                            product.Description = subItem.Description;
                            product.InventoryWay = subItem.InventoryWay;
                            product.Recommend = subItem.Recommend;
                            product.Quota = subItem.Quota;
                            product.IsPutaway = true;
                            product.Sort = subItem.Sort;
                            product.IsProperty = subItem.IsProperty;
                            product.IsStandards = subItem.IsStandards;
                            product.PutawayDate = DateTime.Now;
                            product.AgentsIsPutaway = subItem.AgentsIsPutaway;
                            product.TemplatesGuid = subItem.TemplatesGuid;
                            product.CommissionType = subItem.CommissionType;
                            product.FirstCommissionAmount = subItem.FirstCommissionAmount;
                            product.SecondCommissionAmount = subItem.SecondCommissionAmount;
                            product.ThirdCommissionAmount = subItem.ThirdCommissionAmount;
                            product.NoDelivery = subItem.NoDelivery;
                            product.NoReceive = subItem.NoReceive;
                            product.CategoryCode = subItem.CategoryCode;
                            product.ProductClassify = subItem.ProductClassify;
                            product.SMerchantGuid = agentFlagShip.MerchantGuid;
                            if (subItem.ProductCategoryGuid != null)
                            {
                                var category = addList.FirstOrDefault(a => a.MerchantGuid == entity.MerchantGuid && a.OriginalProductCategoryGuid == subItem.ProductCategoryGuid);
                                if (category != null) product.ProductCategoryGuid = category.ProductCategoryGuid;
                            }
                            product.EntityState = EntityStates.ToBeAdd;
                            listProduct.Add(product);
                        }
                        queryProduct.AddList(listProduct);
                    }
                    #endregion

                    //复制类型、规格、规格名、规格值
                    Guid?[] guids = new Guid?[] { entity.MerchantGuid };
                    Result result;
                    result = Products.ProductsManage.ImportSKUInfo(guids, tran);
                    if (result.State)
                    {
                        //var list = listProduct.Where(a => a.ProductName == "情侣手表爆款男士手表").ToList();
                        //result = ProductSKUManage.CopySKUData(CurrentManage.MerchantGuid, list, tran);
                        result = ProductSKUManage.CopySKUData(CurrentManage.MerchantGuid, listProduct, tran);
                        tran.Commit();
                        return new Result(true);
                    }
                    else
                    {
                        tran.Rollback();
                        return result;
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return new Result(false, ex.Message);
                }
            }
        }

        public static Result SaveFlagShipGroup(T_BAS_Merchants entity, string userid, Guid agentGroupGuid, Guid? AgentProductDiscountGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    tran.BeginTransaction();

                    var queryMerchant = Factory.CreateT_BAS_Merchants(tran);
                    var queryAgentsFlagship = Factory.CreateT_BAS_AgentsFlagship(tran);
                    var queryProductCategory = Factory.CreateT_BAS_ProductCategorys(tran);
                    var queryProduct = Factory.CreateT_BAS_Products(tran);
                    var queryProductType = Factory.CreateT_BAS_ProductType(tran);
                    var queryProductSKU = Factory.CreateT_BAS_ProductSKU(tran);
                    var queryProdure = Factory.CreateProcedure(tran);
                    var queryFactorageAccount = Factory.CreateT_BAS_FactorageAccount(tran);
                    var queryOpenAgentsApply = Factory.CreateT_BAS_OpenAgentsApply(tran);
                    var currMerchant = CurrentManage.MerchantGuid;


                    //得到顶级商家Guid
                    var topAgent = GetTopAgent(currMerchant);
                    if (topAgent == null) return new Result(false, "该代理总部不存在！");
                    var topMerchant = queryMerchant.GetDataByGuid(topAgent.MerchantGuid.Value, false);
                    if (topMerchant == null) return new Result(false, "该代理总部不存在！");

                    //获取当前代理规则
                    var rule = AgentRulesManage.GetUnifyFlagshipParaByGro(agentGroupGuid);

                    //可发展代理总数
                    var canDevelopCount = GetFlagPackMerchantNum();
                    //已发展代理总数
                    var haveDevelopCount = GetAgentCountFromTopToBottom(topAgent.MerchantGuid.Value);
                    if (haveDevelopCount >= canDevelopCount)
                    {
                        tran.Commit();
                        return new Result(false, "对不起，该旗舰版发展代理数超限");
                    }

                    //添加商家
                    var merchantIsext = queryMerchant.GetFirstData(a => a.UserID == entity.UserID);
                    if (merchantIsext != null)
                    {
                        tran.Commit();
                        return new Result(false, "对不起，该代理商ID已存在");
                    }
                    var openAgentsApply = queryOpenAgentsApply.GetFirstData(a => a.UserID == userid, isFilterMerchant: false);
                    if (openAgentsApply == null) return new Result(false, "对不起，该代理商申请不存在！");
                    //更新代理商申请状态
                    queryOpenAgentsApply.Update(a => new Object[] { a.ApplyState == DictionaryConst.AgentApplyState.AuditPass }, a => a.OpenAgentsApplyGuid == openAgentsApply.OpenAgentsApplyGuid, isFilterMerchant: false);
                    //更新旗舰版商户开通数量
                    topAgent.OpenMerchandNum = topAgent.OpenMerchandNum == null ? 1 : topAgent.OpenMerchandNum.Value + 1;
                    queryAgentsFlagship.Update(a => new object[] { a.OpenMerchandNum == topAgent.OpenMerchandNum }, a => a.AgentsFlagshipGuid == topAgent.AgentsFlagshipGuid, false);

                    //获取当前开通商家的上级代理
                    var fatherFlagship = queryAgentsFlagship.GetFirstData(a => a.MerchantGuid == openAgentsApply.FatherMerchantGuid, isFilterMerchant: false);
                    var flagshipGroupGuid = entity.AgentGuid;

                    //if (rule.UserWeChatType == AgentRuleConst.UserWeChatType.总部)
                    //{
                    //    entity.WeChatGuid = topMerchant.WeChatGuid;
                    //}

                    entity.MerchantGuid = Guid.NewGuid();
                    entity.AgentGuid = fatherFlagship == null ? Guid.Empty : fatherFlagship.AgentsFlagshipGuid;
                    entity.StoreState = true;
                    entity.CreateDate = DateTime.Now;
                    entity.ExpireDate = Convert.ToDateTime(entity.CreateDate).AddYears(3);
                    entity.IsEnable = true;
                    entity.UserType = DictionaryConst.Versionb.AgentFlagShip;
                    entity.Password = Utils.Md5(entity.Password);
                    entity.SMerchantGuid = entity.MerchantGuid;
                    queryMerchant.Add(entity);

                    //添加旗舰版下级商户
                    T_BAS_AgentsFlagship agentFlagShip = new T_BAS_AgentsFlagship();
                    agentFlagShip.AgentsFlagshipGuid = Guid.NewGuid();
                    agentFlagShip.MerchantGuid = entity.MerchantGuid;
                    agentFlagShip.FlagshipGroupGuid = flagshipGroupGuid.Value;
                    agentFlagShip.FatherMerchantGuid = openAgentsApply.FatherMerchantGuid;
                    agentFlagShip.TopMerchantGuid = currMerchant;
                    agentFlagShip.SMerchantGuid = entity.MerchantGuid;
                    agentFlagShip.AgentProductDiscountGuid = AgentProductDiscountGuid;
                    if (AgentProductDiscountGuid != null)
                    {
                        var dis = AgentProductDisManage.GetAgentProDisByFk(AgentProductDiscountGuid);
                        agentFlagShip.PaymentType = dis.PaymentType;
                        agentFlagShip.PaymentMoney = dis.PaymentMoney;
                        agentFlagShip.Discount = dis.Discount;
                    }

                    queryAgentsFlagship.Add(agentFlagShip);

                    #region 新旗舰版
                    if (rule.AgentsOpenAgents > 0)
                    {
                        if (AgentAccountManage.IsCountFsBalance)
                        {
                            return new Result(false, "系统繁忙，请稍后重试");
                        }
                        //获取账户可用余额
                        var available = 0m;
                        var freeze = 0m;
                        AgentCommissionManage.GetAvailableAndFreeze(openAgentsApply.FatherMerchantGuid.Value, ref available, ref freeze);
                        available += rule.AgentsOpenAgents.Value;


                        queryMerchant.Update(c => new object[] { 
                            c.FsBalance==available
                        }, c => c.MerchantGuid == openAgentsApply.FatherMerchantGuid, isFilterMerchant: false);

                        //写入流水
                        string tradingcode = DateTime.Now.ToString("yyyyMMddHHmmss") + string.Format("{0:D2}", AgentCommissionConst.TradingType.发展代理商获得佣金);
                        var account = new T_BAS_FactorageAccount()
                        {
                            FactorageAccountGuid = Guid.NewGuid(),
                            MerchantGuid = openAgentsApply.FatherMerchantGuid,
                            TradingCode = tradingcode,
                            AvailableBalance = available,
                            TradingType = AgentCommissionConst.TradingType.发展代理商获得佣金,
                            FactorageSubjectGuid = openAgentsApply.OpenAgentsApplyGuid,
                            TradingDate = DateTime.Now,
                            TradingAmount = rule.AgentsOpenAgents.Value
                        };
                        queryFactorageAccount.Add(account);
                    }
                    #endregion
                    if (AgentAccountManage.IsCountFsBalance)
                    {
                        return new Result(false, "系统繁忙，请稍后重试");
                    }
                    tran.Commit();
                    return new Result(true);


                    #region

                    List<T_BAS_Products> listProduct = new List<T_BAS_Products>();
                    List<T_BAS_ProductCategorys> addList = new List<T_BAS_ProductCategorys>();
                    var topType = queryProductCategory.GetList(a => a.MerchantGuid == topAgent.MerchantGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                    if (topType.Count > 0)
                    {
                        List<T_BAS_ProductCategorys> lstType = new List<T_BAS_ProductCategorys>();

                        lstType = topType.OrderBy(a => a.Levels).ThenBy(a => a.Sort).ToList();
                        foreach (var item in lstType)
                        {

                            var categoryguid = Guid.NewGuid();
                            var _entity = new T_BAS_ProductCategorys();
                            _entity.OriginalProductCategoryGuid = item.ProductCategoryGuid;
                            _entity.SMerchantGuid = CurrentManage.MerchantGuid;
                            _entity.CategoryCode = item.CategoryCode;
                            _entity.CategoryName = item.CategoryName;
                            _entity.Flag = item.Flag;
                            _entity.Levels = item.Levels;
                            _entity.MerchantGuid = agentFlagShip.MerchantGuid;
                            _entity.Sort = item.Sort;
                            _entity.Url = item.Url;
                            if (item.ParentGuid != null)
                            {
                                var model = addList.FirstOrDefault(a => a.OriginalProductCategoryGuid == item.ParentGuid && a.MerchantGuid == agentFlagShip.MerchantGuid);
                                if (model != null) _entity.ParentGuid = model.ProductCategoryGuid;
                            }
                            var model_category = addList.FirstOrDefault(a => a.MerchantGuid == agentFlagShip.MerchantGuid && a.CategoryName == item.CategoryName);
                            if (model_category == null)
                            {
                                _entity.ProductCategoryGuid = categoryguid;
                                queryProductCategory.Add(_entity);
                            }
                            else
                            {
                                _entity.ProductCategoryGuid = model_category.ProductCategoryGuid;
                                queryProductCategory.Update(_entity, false);
                            }
                            addList.Add(_entity);
                        }
                    }
                    var topProduct = queryProduct.GetList(a => a.MerchantGuid == topAgent.MerchantGuid && a.IsAgentsProduct == true, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                    if (topProduct.Count > 0)
                    {
                        string basePath = AppDomain.CurrentDomain.BaseDirectory + @"upload\qrcode\";
                        foreach (var subItem in topProduct)
                        {
                            //商品
                            T_BAS_Products product = new T_BAS_Products();
                            product.OriginalProductGuid = subItem.ProductGuid;
                            product.ProductGuid = Guid.NewGuid();
                            product.ProductTypeGuid = subItem.ProductTypeGuid;
                            product.MerchantGuid = agentFlagShip.MerchantGuid;
                            product.ProductName = subItem.ProductName;
                            product.ProductUrl = "http://" + entity.UserID + string.Format(".shop.{0}/wxshop/productinfo?productsguid={1}", CurrentManage.DomainWxRoot, product.ProductGuid);
                            var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + RadomCode.DigitalCode(3) + ".png";
                            if (Common.QrCodeHelper.GenerationQrCode(product.ProductUrl, "", basePath + fileName))
                            {
                                product.QRCodeUrl = "/upload/qrcode/" + fileName;
                            }
                            product.ProductCode = subItem.ProductCode;
                            product.MarketPrice = subItem.MarketPrice;
                            product.Price = subItem.Price;
                            product.AgentPrice = subItem.AgentPrice;
                            product.MinPrice = subItem.MinPrice;
                            product.MaxPrice = subItem.MaxPrice;
                            product.IsAgentsProduct = false;
                            product.Inventory = subItem.Inventory;
                            product.Weight = subItem.Weight;
                            product.SalesVolume = subItem.SalesVolume;
                            product.BaseSalesVolume = subItem.BaseSalesVolume;
                            product.ProductImage = subItem.ProductImage;
                            product.ProductImage1 = subItem.ProductImage1;
                            product.ProductImage2 = subItem.ProductImage2;
                            product.ProductImage3 = subItem.ProductImage3;
                            product.ProductImage4 = subItem.ProductImage4;
                            product.ProductImage5 = subItem.ProductImage5;
                            product.FirstCommission = subItem.FirstCommission;
                            product.SecondCommission = subItem.SecondCommission;
                            product.ThirdCommission = subItem.ThirdCommission;
                            product.IsDefault = subItem.IsDefault;
                            product.Description = subItem.Description;
                            product.InventoryWay = subItem.InventoryWay;
                            product.Recommend = subItem.Recommend;
                            product.Quota = subItem.Quota;
                            product.IsPutaway = true;
                            product.Sort = subItem.Sort;
                            product.IsProperty = subItem.IsProperty;
                            product.IsStandards = subItem.IsStandards;
                            product.PutawayDate = DateTime.Now;
                            product.AgentsIsPutaway = subItem.AgentsIsPutaway;
                            product.TemplatesGuid = subItem.TemplatesGuid;
                            product.CommissionType = subItem.CommissionType;
                            product.FirstCommissionAmount = subItem.FirstCommissionAmount;
                            product.SecondCommissionAmount = subItem.SecondCommissionAmount;
                            product.ThirdCommissionAmount = subItem.ThirdCommissionAmount;
                            product.NoDelivery = subItem.NoDelivery;
                            product.NoReceive = subItem.NoReceive;
                            product.CategoryCode = subItem.CategoryCode;
                            product.ProductClassify = subItem.ProductClassify;
                            product.SMerchantGuid = agentFlagShip.MerchantGuid;
                            if (subItem.ProductCategoryGuid != null)
                            {
                                var category = addList.FirstOrDefault(a => a.MerchantGuid == entity.MerchantGuid && a.OriginalProductCategoryGuid == subItem.ProductCategoryGuid);
                                if (category != null) product.ProductCategoryGuid = category.ProductCategoryGuid;
                            }
                            product.EntityState = EntityStates.ToBeAdd;
                            listProduct.Add(product);
                        }
                        queryProduct.AddList(listProduct);
                    }
                    #endregion

                    //复制类型、规格、规格名、规格值
                    Guid?[] guids = new Guid?[] { entity.MerchantGuid };
                    Result result;
                    result = Products.ProductsManage.ImportSKUInfo(guids, tran);
                    if (result.State)
                    {
                        //var list = listProduct.Where(a => a.ProductName == "情侣手表爆款男士手表").ToList();
                        //result = ProductSKUManage.CopySKUData(CurrentManage.MerchantGuid, list, tran);
                        result = ProductSKUManage.CopySKUData(CurrentManage.MerchantGuid, listProduct, tran);
                        tran.Commit();
                        return new Result(true);
                    }
                    else
                    {
                        tran.Rollback();
                        return result;
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return new Result(false, ex.Message);
                }
            }
        }

        public static List<T_BAS_MerchantsAgent> GetMerchantPageListGroup(GridModel gridModel, Guid? merchantGuid)
        {
            using (var tran = new SqlRTransaction())
            {

                var queryMerchant = Factory.CreateT_BAS_MerchantsAgent(tran);
                var guids = AgentAuditManage.GetAllSubordinateAgentByMerGuid(CurrentManage.MerchantGuid);
                if (merchantGuid == null)
                {
                    return queryMerchant.GetPageList(gridModel, c => c.MerchantGuid.SqlIn(guids.Select(a => a.Value).ToArray()), isFilterMerchant: false);
                }
                else
                {
                    return queryMerchant.GetPageList(gridModel, c => c.MerchantGuid == merchantGuid, isFilterMerchant: false);
                }


                //List<string> merchantList = new List<string>();
                //switch (searchType)
                //{
                //    case "UserID":
                //        return queryMerchant.GetPageList(gridModel, a => a.MerchantGuid.SqlIn(guids) && a.UserID.SqlLike(searchText), true, p => p.MerchantGuid, isFilterMerchant: false);
                //    case "UpperAgent":
                //        //根据上级代理商，从T_BAS_AgentsFlagship找到
                //        var resultMerchant = queryMerchant.GetList(a => a.UserID.SqlLike(searchText), isFilterMerchant: false);
                //        if (resultMerchant.Count > 0)
                //        {
                //            List<string> fatherList = new List<string>();
                //            foreach (var item in resultMerchant)
                //            {
                //                fatherList.Add(item.MerchantGuid.ToString());
                //            }
                //            var flagShipAgentResult = queryflagShipAgent.GetList(a => a.FatherMerchantGuid.SqlIn(fatherList.ToArray()));
                //            if (flagShipAgentResult.Count > 0)
                //            {
                //                foreach (var item in flagShipAgentResult)
                //                {
                //                    merchantList.Add(item.MerchantGuid.ToString());
                //                }
                //            }
                //        }
                //        if (merchantList.Count > 0)
                //        {
                //            return queryMerchant.GetPageList(gridModel, a => a.MerchantGuid.SqlIn(guids) && a.MerchantGuid.SqlIn(merchantList.ToArray()), true, p => p.MerchantGuid, isFilterMerchant: false);
                //        }
                //        else
                //        {
                //            return queryMerchant.GetPageList(gridModel, a => a.MerchantGuid.SqlIn(guids) && a.MerchantGuid == Guid.NewGuid(), true, p => p.MerchantGuid, isFilterMerchant: false);
                //        }
                //    default:
                //        return queryMerchant.GetPageList(gridModel, a => a.MerchantGuid.SqlIn(guids), true, p => p.MerchantGuid, isFilterMerchant: false);
                //}

                //}
                return new List<T_BAS_MerchantsAgent>();
            }
        }

        public static Result ForbiddenFlagShip(Guid entityGuid, string stateShow)
        {
            if (entityGuid == Guid.Empty) return new Result(false, "数据为空！");
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                var queryResult = query.GetFirstData(a => a.MerchantGuid == entityGuid);
                if (stateShow == "禁用")
                {
                    //queryResult.StoreState = false;
                    queryResult.IsEnable = false;
                }
                else
                {
                    //queryResult.StoreState = true;
                    queryResult.IsEnable = true;
                }
                query.Update(queryResult);
            }
            return new Result(true);
        }

        public static Result MerchantUpdatePwd(Guid entityGuid, string newPassword)
        {
            if (entityGuid == Guid.Empty) return new Result(false, "数据为空！");
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                var queryResult = query.GetFirstData(a => a.MerchantGuid == entityGuid);
                queryResult.Password = Utils.Md5(newPassword);
                query.Update(queryResult);
            }
            return new Result(true);
        }

        public static int? ProductPutAway(string type, Guid? merchantGuid)
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                if (type == "上架")
                {
                    return query.GetCount(a => a.MerchantGuid == merchantGuid && a.IsPutaway == true);
                }
                return query.GetCount(a => a.MerchantGuid == merchantGuid && a.IsPutaway == false);
            }
        }

        public static string GetUpperAgent(Guid? merchantGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                var queryAgent = Factory.CreateT_BAS_AgentsFlagship(tran);
                var modelResult = queryAgent.GetFirstData(a => a.MerchantGuid == merchantGuid);
                if (modelResult != null)
                {
                    var queryMerchant = Factory.CreateT_BAS_Merchants(tran);
                    var merchantModel = queryMerchant.GetFirstData(a => a.MerchantGuid == modelResult.FatherMerchantGuid);
                    if (merchantModel != null)
                    {
                        return merchantModel.UserID;
                    }
                }
                return "";
            }
        }

        public static int? GetTotalAgent(Guid? merchantGuid)
        {
            using (var query = Factory.CreateT_BAS_AgentsFlagship())
            {
                List<string> guidList = new List<string>();
                guidList.Add(merchantGuid.ToString());
                int totalCount = 0;
                bool flag = true;
                while (flag)
                {
                    var queryResult = query.GetList(a => a.FatherMerchantGuid.SqlIn(guidList.ToArray()), true, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                    if (queryResult.Count > 0)
                    {
                        totalCount += queryResult.Count;
                        var list = queryResult.Select(p => p.MerchantGuid).ToList();
                        guidList = new List<string>();
                        for (int i = 0; i < list.Count; i++)
                        {
                            guidList.Add(list[i].ToString());
                        }
                    }
                    else
                    {
                        flag = false;
                    }
                }
                return totalCount;
            }
        }

        public static Dictionary<int, string> GetVersionb()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();

            dic.Add((int)DictionaryConst.Versionb.Syb, "直营版");
            dic.Add((int)DictionaryConst.Versionb.Flagship, "总部版");
            dic.Add((int)DictionaryConst.Versionb.TempTestSys, "试用版(5天)");
            dic.Add((int)DictionaryConst.Versionb.Basic, "基础版");

            return dic;
        }

        public static Result GetCanOpenAgentCount(Guid? groupGuid)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    var queryAgent = Factory.CreateT_BAS_AgentsFlagship(tran);
                    var result = queryAgent.GetList(a => a.FatherMerchantGuid == CurrentManage.MerchantGuid && a.FlagshipGroupGuid == groupGuid);
                    return new Result(true, result.Count.ToString());
                }
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        public static int? GetFlagPackMerchantNum()
        {
            var currentGuid = GetTopestGuidByCurrentGuid(CurrentManage.MerchantGuid);
            using (var tran = new RFramework.SQLServer.SqlRTransaction())
            {
                var queryAgent = Factory.CreateT_BAS_AgentsFlagship(tran);
                var agentResult = queryAgent.GetFirstData(a => a.MerchantGuid == currentGuid, false, null, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                if (agentResult != null)
                {
                    var queryPack = Factory.CreateT_BAS_FlagshipPack(tran);
                    var packResult = queryPack.GetFirstData(a => a.FlagshipPackGuid == agentResult.FlagshipPackGuid, false, null, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                    return packResult.MerchantNum;
                }
                return 0;
            }
        }
        /// <summary>
        /// 旗舰版商家可开通商家数量
        /// </summary>
        /// <returns></returns>
        public static int? GetOpenMaxMerchandNum()
        {
            var currentGuid = GetTopestGuidByCurrentGuid(CurrentManage.MerchantGuid);
            using (var tran = new RFramework.SQLServer.SqlRTransaction())
            {
                var queryAgent = Factory.CreateT_BAS_AgentsFlagship(tran);
                var agentResult = queryAgent.GetFirstData(a => a.MerchantGuid == currentGuid, false, null, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                if (agentResult != null)
                {
                    int maxNum = agentResult.OpenMerchanMaxNum == null ? 0 : agentResult.OpenMerchanMaxNum.Value;
                    int num = agentResult.OpenMerchandNum == null ? 0 : agentResult.OpenMerchandNum.Value;
                    return maxNum - num;
                }
                return 0;
            }
        }
        /// <summary>
        /// 旗舰版商家已商家数量
        /// </summary>
        /// <returns></returns>
        public static int? GetOpenMerchandNum()
        {
            var currentGuid = GetTopestGuidByCurrentGuid(CurrentManage.MerchantGuid);
            using (var tran = new RFramework.SQLServer.SqlRTransaction())
            {
                var queryAgent = Factory.CreateT_BAS_AgentsFlagship(tran);
                var agentResult = queryAgent.GetFirstData(a => a.MerchantGuid == currentGuid, false, null, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                if (agentResult != null)
                {
                    int num = agentResult.OpenMerchandNum == null ? 0 : agentResult.OpenMerchandNum.Value;
                    return num;
                }
                return 0;
            }
        }


        public static int? GetAgentCountFromTopToBottom(Guid? currentGuid)
        {
            using (var query = Factory.CreateT_BAS_AgentsFlagship())
            {
                List<string> guidList = new List<string>();
                guidList.Add(currentGuid.ToString());
                int totalCount = 0;
                bool flag = true;
                while (flag)
                {
                    var queryResult = query.GetList(a => a.FatherMerchantGuid.SqlIn(guidList.ToArray()), true, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                    if (queryResult.Count > 0)
                    {
                        totalCount += queryResult.Count;
                        var list = queryResult.Select(p => p.MerchantGuid).ToList();
                        guidList = new List<string>();
                        for (int i = 0; i < list.Count; i++)
                        {
                            guidList.Add(list[i].ToString());
                        }
                    }
                    else
                    {
                        flag = false;
                    }
                }
                return totalCount;
            }
        }

        public static int? GetAgentCountFromBottomToTop(Guid? currentGuid)
        {
            return 0;
        }

        public static Guid? GetTopestGuidByCurrentGuid(Guid currentGuid)
        {
            using (var query = Factory.CreateT_BAS_AgentsFlagship())
            {
                Guid guid = new Guid();
                bool flag = true;
                while (flag)
                {
                    var queryResult = query.GetFirstData(a => a.MerchantGuid == currentGuid, false, null, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                    if (queryResult != null)
                    {
                        if (queryResult.FatherMerchantGuid == new Guid() || queryResult.FatherMerchantGuid == null)
                        {
                            flag = false;
                            guid = currentGuid;
                        }
                        else
                        {
                            currentGuid = queryResult.FatherMerchantGuid.Value;
                        }
                    }
                    else
                    {
                        flag = false;
                    }
                }
                return guid;
            }
        }
        /// <summary>
        /// 获取指定代理的旗舰版总部
        /// </summary>
        /// <param name="currentGuid"></param>
        /// <returns></returns>
        public static T_BAS_AgentsFlagship GetTopAgent(Guid currentGuid, SqlRTransaction tran = null)
        {
            using (var query = Factory.CreateT_BAS_AgentsFlagship(tran))
            {
                T_BAS_AgentsFlagship topAgent = null;
                bool flag = true;
                while (flag)
                {
                    var model = query.GetFirstData(a => a.MerchantGuid == currentGuid, false, null, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                    if (model != null)
                    {
                        if (model.FatherMerchantGuid == new Guid() || model.FatherMerchantGuid == null)
                        {
                            flag = false;
                            topAgent = model;
                        }
                        else
                        {
                            currentGuid = model.FatherMerchantGuid.Value;
                        }
                    }
                    else
                    {
                        flag = false;
                    }
                }
                return topAgent;
            }
        }

        /// <summary>
        /// 获取当前登录用户是否是旗舰版总部 by LiJ 
        /// </summary>
        /// <param name="currentGuid"></param>
        /// <returns></returns>
        public static bool IsTop()
        {
            using (var query = Factory.CreateT_BAS_AgentsFlagship())
            {
                var model = query.GetFirstData(a => a.MerchantGuid == CurrentManage.MerchantGuid, false, null, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default);
                if (model == null) return false;
                if (model.FatherMerchantGuid == null || model.FatherMerchantGuid == Guid.Empty) return true;
                return false;
            }
        }

        /// <summary>
        /// 判断指定商家是否为旗舰版总部
        /// </summary>
        /// <returns></returns>
        public static bool IsTopByMer(Guid guid)
        {
            using (var query = Factory.CreateT_BAS_AgentsFlagship())
            {
                var model = query.GetFirstData(a => a.MerchantGuid == guid, false, null, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                if (model == null) return false;
                if (model.FatherMerchantGuid == null || model.FatherMerchantGuid == Guid.Empty) return true;
                return false;
            }
        }


        /// <summary>
        /// 判断当前登录用户是否为创业板总部
        /// </summary>
        /// <returns></returns>
        public static bool IsMar()
        {
            using (var query = Factory.CreateT_BAS_AgentsFlagship())
            {
                var n = query.IsExist(a => a.MerchantGuid == Common.CurrentManage.MerchantGuid, false, false);
                return !n;
            }
        }

        /// <summary>
        /// 判断指定商家是否为创业板总部
        /// </summary>
        /// <returns></returns>
        public static bool IsMarByMer(Guid guid)
        {
            using (var query = Factory.CreateT_BAS_AgentsFlagship())
            {
                var n = query.IsExist(a => a.MerchantGuid == guid, false, false);
                return !n;
            }
        }


        /// <summary>
        /// 判断当前登录用户是否为总部 Bing 160410
        /// </summary>
        /// <returns></returns>
        public static bool IsTopTe()
        {
            using (var query = Factory.CreateT_BAS_AgentsFlagship())
            {
                var model = query.GetFirstData(a => a.MerchantGuid == Common.CurrentManage.MerchantGuid, false, null, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                if (model == null)
                {
                    return true;
                }
                else
                {
                    if (model.FatherMerchantGuid == null || model.FatherMerchantGuid == Guid.Empty)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
        }

        /// <summary>
        /// 判断指定商家是否为总部 Bing 160410
        /// </summary>
        /// <returns></returns>
        public static bool IsTopTeByMer(Guid guid)
        {
            using (var query = Factory.CreateT_BAS_AgentsFlagship())
            {
                var model = query.GetFirstData(a => a.MerchantGuid == guid, false, null, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                if (model == null)
                {
                    return true;
                }
                else
                {
                    if (model.FatherMerchantGuid == null || model.FatherMerchantGuid == Guid.Empty)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
        }

        /// <summary>
        /// 获取下级代理
        /// </summary>
        /// <returns></returns>
        public static List<T_BAS_Merchants> GetSubMerchantList()
        {
            using (var tran = new SqlRTransaction())
            {
                var listMerchant = new List<T_BAS_Merchants>();
                var query_merchant = Factory.CreateT_BAS_Merchants(tran);
                var guids = AgentAuditManage.GetAllSubordinateAgentByMerGuid(Common.CurrentManage.MerchantGuid);
                if (guids != null && guids.Count > 0)
                {
                    listMerchant = query_merchant.GetList(a => a.MerchantGuid.SqlIn(guids.Select(c => c.Value).ToArray()), isFilterMerchant: false);
                }
                return listMerchant;
            }
        }

        /// <summary>
        /// 更新商家
        /// </summary>
        /// <param name="tran"></param>
        /// <param name="query_distributeOrder"></param>
        /// <param name="query_distributionProp"></param>
        /// <param name="query_merchant"></param>
        /// <param name="merchant"></param>
        /// <returns></returns>
        public static Result UpdateTotalOrders(SqlRTransaction tran, IQuery<T_ST_DistributeOrder> query_distributeOrder, IQuery<T_BAS_DistributionProp> query_distributionProp, IQuery<T_BAS_Merchants> query_merchant, T_BAS_Merchants merchant)
        {
            try
            {
                var query_withdrawsCommission = Factory.CreateT_BAS_WithdrawsCommission(tran);
                List<T_BAS_WithdrawsCommission> list_withdrawsCommission = query_withdrawsCommission.GetList(a => a.MerchantGuid == merchant.ToString() && a.State == DictionaryConst.WithdriwalCom.WithdrawalsSuccess, isFilterMerchant: 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, isFilterMerchant: false);
                    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);
                }
                return new Result(true);
            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }

        public static string GetUserIdByGuid(Guid? guid)
        {
            if (guid == null || guid == Guid.Empty) return "";
            using (var query = Factory.CreateT_BAS_Merchants())
            {
                var model = query.GetDataByGuid(guid.Value);
                if (model == null) return "";
                return model.UserID;
            }
        }
    }
}
