using RFrameGenerate.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Wechat.Model;
using RFramework.SQLQuery;
using weixinopen;
using Wechat;
using RFramework.SQLServer;
using RFramework.SQLQuery.SQLExpands;
using RFrameGenerate.Common;
using RFrameGenerate.Model.PageModel;
using System.Threading.Tasks;

namespace RFrameGenerate.BLL
{
    public class AgentGroupProductsManage
    {

        #region 获取分组商品列表-分页数据
        /// <summary>
        /// 获取分组商品列表-分页数据 
        /// </summary>
        /// <param name="gridModel"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static List<T_BAS_ProductsWithAgent> GetPageListHq(GridModel gridModel, Guid? ProductCategoryGuid, string ProductName)
        {
            using (var query = Factory.CreateT_BAS_ProductsWithAgent())
            {
                var list = query.GetPageList(gridModel, c => c.MerchantGuid == Common.CurrentManage.MerchantGuid && c.ProductCategoryGuid == ProductCategoryGuid && c.ProductName.SqlLike(ProductName), true, c => c.Sort, DAL.Enums.OrderMethods.ASC, RFramework.SQLServer.Enums.LockType.Default, false);
                return list;
            }
        }
        #endregion

        #region 获取代理分组商品列表-分页数据
        /// <summary>
        /// 获取代理分组商品列表-分页数据 
        /// </summary>
        /// <param name="gridModel"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static List<T_BAS_ProductsWithAgentSub> GetPageListSub(GridModel gridModel, Guid? FlagshipGroupGuid, Guid? AgentProductDiscountGuid, Guid? ProductCategoryGuid, string ProductName)
        {
            using (var query = Factory.CreateT_BAS_ProductsWithAgentSub())
            {
                var list = query.GetPageList(gridModel, c => c.FlagshipGroupGuid == FlagshipGroupGuid && c.AgentProductDiscountGuid == AgentProductDiscountGuid && c.ProductCategoryGuid == ProductCategoryGuid && c.ProductName.SqlLike(ProductName), true, null, DAL.Enums.OrderMethods.ASC, RFramework.SQLServer.Enums.LockType.Default);

                return list;
            }
        }
        #endregion

        #region 判断指定商家是否预存代理
        /// <summary>
        /// 判断指定商家是否预存代理
        /// </summary>
        /// <param name="proGuid"></param>
        /// <param name="merGuid"></param>
        /// <param name="discount"></param>
        /// <returns></returns>
        public static bool GetBeAgentPro(Guid merGuid)
        {
            bool b = false;
            using (var queryMer = Factory.CreateT_BAS_MerchantsWithLite())
            {
                var mer = queryMer.GetFirstData(c => c.MerchantGuid == merGuid, isFilterMerchant: false);
                if (mer != null && mer.PaymentType == AgentProductDiscountConst.PaymentType.预存)
                {
                    b = true;
                }
            }
            return b;
        }

        #endregion

        #region 获取指定分组商品指定代理折扣
        /// <summary>
        /// 获取指定分组商品指定代理折扣
        /// </summary>
        /// <param name="proGuid"></param>
        /// <param name="mer"></param>
        /// <returns></returns>
        //public static decimal GetProductGroupDisData(Guid proGuid, T_BAS_MerchantsWithLite mer)
        //{
        //    decimal discount = 100;
        //    using (var queryProDis = Factory.CreateT_BAS_AgentProductDiscountDetail())
        //    {
        //        var dis = queryProDis.GetFirstData(c => c.ProductGuid == proGuid && c.FlagshipGroupGuid == mer.FlagshipGroupGuid.Value && c.AgentProductDiscountGuid == mer.AgentProductDiscountGuid, true, isFilterMerchant: false);//单、双重
        //        discount = dis.Discount.Value;//必须不可空
        //    }
        //    return discount;
        //}

        #endregion

        #region 添加分组商品
        /// <summary>
        /// 添加分组商品
        /// </summary>
        /// <returns></returns>
        public static Result AddProductsAgent(string ProductGuids, Guid FlagshipGroupGuid, decimal Discount, decimal MinPrice, decimal MaxPrice, Guid? AgentProductDiscountGuid = null)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                    var productGuidArr = js.Deserialize<Guid[]>(ProductGuids);

                    var query_pro = Factory.CreateT_BAS_Products(tran);
                    var query_agentPro = Factory.CreateT_BAS_AgentProductDiscountDetail(tran);

                    //暂定
                    var count = query_agentPro.GetCount(c => c.ProductGuid.SqlIn(productGuidArr.Select(g => g.ToString()).ToArray()) && c.FlagshipGroupGuid == FlagshipGroupGuid && c.AgentProductDiscountGuid == AgentProductDiscountGuid, true, isFilterMerchant: false);
                    if (count > 0)
                    {
                        return new Result(false, string.Format("请移除已存在于当前分组中的商品，不可重复添加"));
                    }

                    var entity_pros = query_pro.GetList(c => c.ProductGuid.SqlIn(productGuidArr.Select(g => g.ToString()).ToArray()) && c.MerchantGuid == Common.CurrentManage.MerchantGuid, isFilterMerchant: false);

                    var agentProDisDets = new List<T_BAS_AgentProductDiscountDetail>();
                    entity_pros.ForEach(c =>
                    {
                        agentProDisDets.Add(new T_BAS_AgentProductDiscountDetail()
                        {
                            AgentProductDiscountDetailGuid = Guid.NewGuid(),
                            AgentProductDiscountGuid = AgentProductDiscountGuid,
                            ProductGuid = c.ProductGuid,
                            FlagshipGroupGuid = FlagshipGroupGuid,
                            Discount = Discount,
                            MinPrice = MinPrice,
                            MaxPrice = MaxPrice,
                            AgentDiscountPrice = decimal.Round((c.AgentPrice.Value * Discount / 100), 2, MidpointRounding.AwayFromZero),
                            EntityState = EntityStates.ToBeAdd
                        });
                    });

                    tran.BeginTransaction();
                    query_agentPro.AddList(agentProDisDets);

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

        #endregion

        #region 移除分组商品
        /// <summary>
        /// 移除分组商品
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static Result RemoveProductsAgent(Guid guid)
        {
            using (var tran = new SqlRTransaction())
            {
                try
                {
                    var query_agentPro = Factory.CreateT_BAS_AgentProductDiscountDetail(tran);
                    var queryProAgen = Factory.CreateT_BAS_ProductsWithAgentSub(tran);
                    var queryMer = Factory.CreateT_BAS_MerchantsAgent(tran);
                    var queryPro = Factory.CreateT_BAS_Products(tran);
                    var queryProCate = Factory.CreateT_BAS_ProductCategorys(tran);
                    var queryProType = Factory.CreateT_BAS_ProductType(tran);
                    var queryProSku = Factory.CreateT_BAS_ProductSKU(tran);
                    var queryProSkuName = Factory.CreateT_BAS_ProductSKUName(tran);
                    var queryProSkuValue = Factory.CreateT_BAS_ProductSKUValue(tran);
                    tran.BeginTransaction();

                    var agentProDisDet = queryProAgen.GetFirstData(c => c.AgentProductDiscountDetailGuid == guid);
                    var merchantList = queryMer.GetList(c => c.FlagshipGroupGuid == agentProDisDet.FlagshipGroupGuid && c.AgentProductDiscountGuid == agentProDisDet.AgentProductDiscountGuid, true, isFilterMerchant: false);
                    if (merchantList != null && merchantList.Count > 0)
                    {
                        var merGuids = merchantList.Select(m => m.MerchantGuid.ToString()).ToArray();
                        var productList = queryPro.GetList(c => c.OriginalProductGuid == agentProDisDet.ProductGuid && c.MerchantGuid.SqlIn(merGuids), isFilterMerchant: false);
                        if (productList != null && productList.Count > 0)
                        {
                            var proGuids = productList.Select(p => p.ProductGuid.ToString()).ToArray();
                            queryPro.Delete(c => c.ProductGuid.SqlIn(proGuids) && c.MerchantGuid.SqlIn(merGuids), isFilterMerchant: false);
                            queryProSku.Delete(c => c.ProductGuid.SqlIn(proGuids) && c.MerchantGuid.SqlIn(merGuids), isFilterMerchant: false);
                        }
                    }
                    query_agentPro.Delete(c => c.AgentProductDiscountDetailGuid == guid, isFilterMerchant: false);

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

        }
        #endregion

        #region 同步分组商品-备用
        /// <summary>
        /// 同步分组商品-备用
        /// </summary>
        /// <param name="strArr"></param>
        /// <param name="checkNum">1-基本信息，2-规格信息，3-全部（默认）</param>
        /// <returns></returns>
        public static Result ImportProductAgent2(string strArr, int checkNum, bool includeCom)
        {
            return null;
            #region 备用
            //System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            //var agentProDisDets = js.Deserialize<Guid[]>(strArr);

            //#region 商品信息库
            ////需要导入/同步的代理
            //List<T_BAS_ProductsWithAgentSub> agentProDisDetList = new List<T_BAS_ProductsWithAgentSub>();
            //List<T_BAS_MerchantsAgent> merchantList = new List<T_BAS_MerchantsAgent>();

            ////待导入/同步的商品相关信息
            //List<T_BAS_Products> productList = new List<T_BAS_Products>();
            //List<T_BAS_ProductCategorys> productCategoryList = new List<T_BAS_ProductCategorys>();
            //List<T_BAS_ProductType> productTypeList = new List<T_BAS_ProductType>();
            //List<T_BAS_ProductSKU> productSKUList = new List<T_BAS_ProductSKU>();
            //List<T_BAS_ProductSKUName> productSKUNameList = new List<T_BAS_ProductSKUName>();
            //List<T_BAS_ProductSKUValue> productSKUValueList = new List<T_BAS_ProductSKUValue>();

            ////已选下级的商品相关信息
            //List<T_BAS_Products> productListSub = new List<T_BAS_Products>();
            //List<T_BAS_ProductCategorys> productCategoryListSub = new List<T_BAS_ProductCategorys>();
            //List<T_BAS_ProductType> productTypeListSub = new List<T_BAS_ProductType>();
            //List<T_BAS_ProductSKU> productSKUListSub = new List<T_BAS_ProductSKU>();
            //List<T_BAS_ProductSKUName> productSKUNameListSub = new List<T_BAS_ProductSKUName>();
            //List<T_BAS_ProductSKUValue> productSKUValueListSub = new List<T_BAS_ProductSKUValue>();

            ////待添加/更新的商品相关信息
            //List<T_BAS_Products> addProductListSub = new List<T_BAS_Products>();
            //List<T_BAS_Products> updateProductListSub = new List<T_BAS_Products>();
            //List<T_BAS_ProductCategorys> addProductCategoryListSub = new List<T_BAS_ProductCategorys>();
            //List<T_BAS_ProductType> addProductTypeListSub = new List<T_BAS_ProductType>();
            //List<T_BAS_ProductSKU> addProductSKUSub = new List<T_BAS_ProductSKU>();
            //List<T_BAS_ProductSKU> deleteProductSKUSub = new List<T_BAS_ProductSKU>();
            //#endregion

            //#region 获取最新商品信息库
            //using (var tran = new SqlRTransaction())
            //{
            //    var queryProAgen = Factory.CreateT_BAS_ProductsWithAgentSub(tran);
            //    var queryMer = Factory.CreateT_BAS_MerchantsAgent(tran);
            //    var queryPro = Factory.CreateT_BAS_Products(tran);
            //    var queryProCate = Factory.CreateT_BAS_ProductCategorys(tran);
            //    var queryProType = Factory.CreateT_BAS_ProductType(tran);
            //    var queryProSku = Factory.CreateT_BAS_ProductSKU(tran);
            //    var queryProSkuName = Factory.CreateT_BAS_ProductSKUName(tran);
            //    var queryProSkuValue = Factory.CreateT_BAS_ProductSKUValue(tran);

            //    agentProDisDetList = queryProAgen.GetList(c => c.AgentProductDiscountDetailGuid.SqlIn(agentProDisDets));
            //    if (agentProDisDetList == null || agentProDisDetList.Count == 0)
            //    {
            //        return new Result(false, "请选择需要操作的分组商品");
            //    }

            //    productList = queryPro.GetList(c => c.ProductGuid.SqlIn(agentProDisDetList.Select(d => d.ProductGuid.Value).ToArray()) && c.MerchantGuid == Common.CurrentManage.MerchantGuid);
            //    if (productList == null || productList.Count == 0)
            //    {
            //        return new Result(false, "获取商品信息失败");
            //    }
            //    var errProduct = productList.FirstOrDefault(c => c.AgentPrice == null);
            //    if (errProduct != null)
            //    {
            //        return new Result(false, string.Format("商品未添加代理统一价格：{0}", errProduct.ProductName));
            //    }
            //    merchantList = queryMer.GetList(c => c.FlagshipGroupGuid.SqlIn(agentProDisDetList.Select(d => d.FlagshipGroupGuid).ToArray()), isFilterMerchant: false);
            //    if (merchantList == null || merchantList.Count == 0)
            //    {
            //        return new Result(false, "当前商品组无商家");
            //    }
            //    var cates = productList.Where(p => p.ProductCategoryGuid != null).Select(p => p.ProductCategoryGuid).ToArray();
            //    if (cates != null && cates.Count() > 0)
            //    {
            //        productCategoryList = (queryProCate.GetList(c => c.ProductCategoryGuid.SqlIn(cates) && c.MerchantGuid == Common.CurrentManage.MerchantGuid) ?? new List<T_BAS_ProductCategorys>());
            //    }
            //    var types = productList.Where(p => p.ProductTypeGuid != null).Select(p => p.ProductTypeGuid.ToString()).ToArray();
            //    if (types != null && types.Count() > 0)
            //    {
            //        productTypeList = (queryProType.GetList(c => c.ProductTypeGuid.SqlIn(types) && c.MerchantGuid == Common.CurrentManage.MerchantGuid) ?? new List<T_BAS_ProductType>());
            //    }

            //    productSKUList = (queryProSku.GetList(c => c.ProductGuid.SqlIn(productList.Select(p => p.ProductGuid).ToArray()) && c.MerchantGuid == Common.CurrentManage.MerchantGuid) ?? new List<T_BAS_ProductSKU>());


            //    if (productTypeList != null && productTypeList.Count > 0)
            //    {
            //        productSKUNameList = (queryProSkuName.GetList(c => c.ProductTypeGuid.SqlIn(productTypeList.Select(t => t.ProductTypeGuid.ToString()).ToArray()) && c.MerchantGuid == Common.CurrentManage.MerchantGuid) ?? new List<T_BAS_ProductSKUName>());
            //    }
            //    if (productSKUNameList != null && productSKUNameList.Count > 0)
            //    {
            //        productSKUValueList = (queryProSkuValue.GetList(c => c.ProductSKUNameGuid.SqlIn(productSKUNameList.Select(n => n.ProductSKUNameGuid.ToString()).ToArray()) && c.MerchantGuid == Common.CurrentManage.MerchantGuid) ?? new List<T_BAS_ProductSKUValue>());
            //    }



            //    var proGuids = productList.Select(p => p.ProductGuid.ToString()).ToArray();
            //    var merGuids = merchantList.Select(m => m.MerchantGuid.ToString()).ToArray();

            //    productListSub = (queryPro.GetList(c => c.MerchantGuid.SqlIn(merGuids) && c.OriginalProductGuid.SqlIn(proGuids), isFilterMerchant: false) ?? new List<T_BAS_Products>());
            //    productCategoryListSub = (queryProCate.GetList(c => c.MerchantGuid.SqlIn(merGuids), isFilterMerchant: false) ?? new List<T_BAS_ProductCategorys>());
            //    productTypeListSub = (queryProType.GetList(c => c.MerchantGuid.SqlIn(merGuids), isFilterMerchant: false) ?? new List<T_BAS_ProductType>());
            //    if (productListSub != null && productListSub.Count > 0)
            //    {
            //        productSKUListSub = (queryProSku.GetList(c => c.MerchantGuid.SqlIn(merGuids) && c.ProductGuid.SqlIn(productListSub.Select(p => p.ProductGuid).ToArray()), isFilterMerchant: false) ?? new List<T_BAS_ProductSKU>());
            //    }
            //}
            //#endregion

            //foreach (var agentProDisDet in agentProDisDetList)
            //{
            //    var subMerchants = merchantList.Where(c => c.FlagshipGroupGuid == agentProDisDet.FlagshipGroupGuid).ToList();
            //    if (agentProDisDet.AgentProductDiscountGuid != null)
            //    {
            //        subMerchants = subMerchants.Where(c => c.AgentProductDiscountGuid == agentProDisDet.AgentProductDiscountGuid).ToList();
            //    }
            //    if (subMerchants == null || subMerchants.Count == 0)
            //    {
            //        continue;
            //    }

            //    foreach (var subMer in subMerchants)
            //    {
            //        #region 添加商品基本信息
            //        var topPro = productList.FirstOrDefault(c => c.ProductGuid == agentProDisDet.ProductGuid);
            //        if (topPro == null)
            //        {
            //            return new Result(false, "没有找到此商品");
            //        }
            //        var isNewProSub = true;
            //        var subProGuid = Guid.Empty;
            //        var subPro = productListSub.FirstOrDefault(c => c.OriginalProductGuid == topPro.ProductGuid && c.MerchantGuid == subMer.MerchantGuid);
            //        if (subPro != null)
            //        {
            //            isNewProSub = false;
            //            subProGuid = subPro.ProductGuid;
            //        }

            //        if (checkNum != 2)
            //        {
            //            if (subPro == null)
            //            {
            //                subPro = new T_BAS_Products();
            //                subPro.EntityState = EntityStates.ToBeAdd;
            //                subPro.ProductGuid = Guid.NewGuid();
            //                addProductListSub.Add(subPro);
            //            }
            //            else
            //            {
            //                subPro.EntityState = EntityStates.ToBeUpdated;
            //                updateProductListSub.Add(subPro);
            //            }
            //            subPro.Price = topPro.Price;
            //            subPro.MinPrice = decimal.Round((topPro.Price * (100 - agentProDisDet.MinPrice) / 100).Value, 2, MidpointRounding.AwayFromZero);
            //            subPro.MaxPrice = decimal.Round((topPro.Price * (100 + agentProDisDet.MaxPrice) / 100).Value, 2, MidpointRounding.AwayFromZero);
            //            subPro.MerchantGuid = subMer.MerchantGuid;
            //            subPro.SMerchantGuid = subMer.MerchantGuid;
            //            subPro.ProductUrl = "http://" + subMer.UserID + string.Format(".shop.{0}/wxshop/productinfo?productsguid={1}", CurrentManage.DomainWxRoot, subPro.ProductGuid);
            //            var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + RFrameGenerate.Common.RadomCode.DigitalCode(3) + ".png";
            //            if (Common.QrCodeHelper.GenerationQrCode(subPro.ProductUrl, "", AppDomain.CurrentDomain.BaseDirectory + @"upload\qrcode\" + fileName))
            //            {
            //                subPro.QRCodeUrl = "/upload/qrcode/" + fileName;
            //            }

            //            subPro.IsAgentsProduct = false;
            //            subPro.IsPutaway = true;
            //            subPro.ProductName = topPro.ProductName;
            //            subPro.ProductCode = topPro.ProductCode;
            //            subPro.MarketPrice = topPro.MarketPrice;

            //            subPro.Inventory = topPro.Inventory;
            //            subPro.Weight = topPro.Weight;
            //            subPro.SalesVolume = 0;
            //            subPro.BaseSalesVolume = topPro.BaseSalesVolume;
            //            subPro.ProductImage = topPro.ProductImage;
            //            subPro.ProductImage1 = topPro.ProductImage1;
            //            subPro.ProductImage2 = topPro.ProductImage2;
            //            subPro.ProductImage3 = topPro.ProductImage3;
            //            subPro.ProductImage4 = topPro.ProductImage4;
            //            subPro.ProductImage5 = topPro.ProductImage5;
            //            subPro.FirstCommission = topPro.FirstCommission;
            //            subPro.SecondCommission = topPro.SecondCommission;
            //            subPro.ThirdCommission = topPro.ThirdCommission;
            //            subPro.IsDefault = topPro.IsDefault;
            //            subPro.Description = topPro.Description;
            //            subPro.InventoryWay = topPro.InventoryWay;
            //            subPro.Recommend = topPro.Recommend;
            //            subPro.Quota = topPro.Quota;
            //            subPro.Sort = topPro.Sort;
            //            subPro.IsProperty = topPro.IsProperty;
            //            subPro.IsStandards = topPro.IsStandards;
            //            subPro.PutawayDate = DateTime.Now;
            //            subPro.OriginalProductGuid = topPro.ProductGuid;
            //            subPro.AgentsIsPutaway = topPro.AgentsIsPutaway;
            //            if (subMer.GoodsDeliveryType == AgentRuleConst.GoodsDeliveryType.总部)
            //            {
            //                subPro.TemplatesGuid = topPro.TemplatesGuid;
            //            }

            //            subPro.CommissionType = topPro.CommissionType;
            //            subPro.FirstCommissionAmount = topPro.FirstCommissionAmount;
            //            subPro.SecondCommissionAmount = topPro.SecondCommissionAmount;
            //            subPro.ThirdCommissionAmount = topPro.ThirdCommissionAmount;
            //            subPro.NoDelivery = topPro.NoDelivery;
            //            subPro.NoReceive = topPro.NoReceive;
            //            subPro.CategoryCode = topPro.CategoryCode;
            //            subPro.ProductClassify = topPro.ProductClassify;
            //            //subPro.AgentPrice = agentProDisDet.AgentDiscountPrice;
            //            subPro.AgentPrice = topPro.AgentPrice;

            //            if (topPro.ProductCategoryGuid != null && topPro.ProductCategoryGuid != Guid.Empty)
            //            {
            //                var subCate = productCategoryListSub.FirstOrDefault(c => c.OriginalProductCategoryGuid == topPro.ProductCategoryGuid && c.MerchantGuid == subMer.MerchantGuid);
            //                if (subCate == null)
            //                {
            //                    subCate = addProductCategoryListSub.FirstOrDefault(c => c.OriginalProductCategoryGuid == topPro.ProductCategoryGuid && c.MerchantGuid == subMer.MerchantGuid);
            //                }
            //                if (subCate != null)
            //                {
            //                    subPro.ProductCategoryGuid = subCate.ProductCategoryGuid;
            //                }
            //                else
            //                {
            //                    var topCate = productCategoryList.FirstOrDefault(c => c.ProductCategoryGuid == topPro.ProductCategoryGuid);
            //                    subCate = productCategoryListSub.FirstOrDefault(c => c.CategoryName == topCate.CategoryName && c.MerchantGuid == subMer.MerchantGuid);
            //                    if (subCate != null)
            //                    {
            //                        subPro.ProductCategoryGuid = subCate.ProductCategoryGuid;
            //                    }
            //                    else
            //                    {
            //                        subPro.ProductCategoryGuid = Guid.NewGuid();
            //                        var newCate = new T_BAS_ProductCategorys();
            //                        newCate.MerchantGuid = subMer.MerchantGuid;
            //                        newCate.SMerchantGuid = subMer.MerchantGuid;
            //                        newCate.ProductCategoryGuid = subPro.ProductCategoryGuid;
            //                        newCate.OriginalProductCategoryGuid = topCate.ProductCategoryGuid;
            //                        newCate.Levels = topCate.Levels;
            //                        newCate.ParentGuid = topCate.ParentGuid;
            //                        newCate.Sort = topCate.Sort;
            //                        newCate.CategoryCode = topCate.CategoryCode;
            //                        newCate.CategoryName = topCate.CategoryName;
            //                        newCate.Flag = topCate.Flag;
            //                        newCate.Url = topCate.Url;
            //                        newCate.EntityState = EntityStates.ToBeAdd;
            //                        addProductCategoryListSub.Add(newCate);
            //                    }
            //                }
            //            }

            //            if (topPro.ProductTypeGuid != null && topPro.ProductTypeGuid != Guid.Empty)
            //            {
            //                var subType = productTypeListSub.FirstOrDefault(c => c.OriginalProductTypeGuid == topPro.ProductTypeGuid && c.MerchantGuid == subMer.MerchantGuid);
            //                if (subType == null)
            //                {
            //                    subType = addProductTypeListSub.FirstOrDefault(c => c.OriginalProductTypeGuid == topPro.ProductTypeGuid && c.MerchantGuid == subMer.MerchantGuid);
            //                }
            //                if (subType != null)
            //                {
            //                    subPro.ProductTypeGuid = subType.ProductTypeGuid;
            //                }
            //                else
            //                {
            //                    var topType = productTypeList.FirstOrDefault(c => c.ProductTypeGuid == topPro.ProductTypeGuid);
            //                    subPro.ProductTypeGuid = Guid.NewGuid();
            //                    var newType = new T_BAS_ProductType();
            //                    newType.MerchantGuid = subMer.MerchantGuid;
            //                    newType.SMerchantGuid = subMer.MerchantGuid;
            //                    newType.OriginalProductTypeGuid = topType.ProductTypeGuid;
            //                    newType.ProductTypeGuid = subPro.ProductTypeGuid.Value;
            //                    newType.ProductTypeName = topType.ProductTypeName;
            //                    newType.Remark = topType.Remark;
            //                    newType.Sort = topType.Sort;
            //                    newType.EntityState = EntityStates.ToBeAdd;
            //                    addProductTypeListSub.Add(newType);
            //                }
            //            }
            //        }
            //        #endregion


            //        #region 添加商品规格信息
            //        if (checkNum == 3 || (checkNum == 1 && isNewProSub) || (checkNum == 2 && isNewProSub == false))
            //        {

            //            var deleteSkus = productSKUListSub.Where(c => c.ProductGuid == subProGuid && c.MerchantGuid == subMer.MerchantGuid).ToList();
            //            if (deleteSkus != null && deleteSkus.Count > 0)
            //            {
            //                deleteProductSKUSub.AddRange(deleteSkus);
            //            }
            //            var topSkus = productSKUList.Where(c => c.ProductGuid == topPro.ProductGuid);
            //            if (topSkus != null && topSkus.Count() > 0)
            //            {
            //                foreach (var topSku in topSkus)
            //                {
            //                    var newSku = new T_BAS_ProductSKU();
            //                    newSku.ProductSKUGuid = Guid.NewGuid();
            //                    //                                newSku.AgentPrice = decimal.Round((topSku.AgentPrice * agentProDisDet.Discount / 100).Value, 2, 
            //                    //MidpointRounding.AwayFromZero);
            //                    newSku.AgentPrice = topSku.AgentPrice;
            //                    newSku.Code = topSku.Code;
            //                    newSku.Invenotory = topSku.Invenotory;
            //                    newSku.MerchantGuid = subMer.MerchantGuid;
            //                    newSku.SMerchantGuid = subMer.MerchantGuid;
            //                    newSku.OriginalProductSKUGuid = topSku.ProductSKUGuid;
            //                    newSku.Price = topSku.Price;

            //                    newSku.PriceMin = decimal.Round((topSku.Price * (100 - agentProDisDet.MinPrice) / 100).Value, 2, MidpointRounding.AwayFromZero);
            //                    newSku.PriceMax = decimal.Round((topSku.Price * (100 + agentProDisDet.MaxPrice) / 100).Value, 2, MidpointRounding.AwayFromZero);
            //                    newSku.ProductGuid = subPro.ProductGuid;
            //                    newSku.ProductSKUGroupGuid = topSku.ProductSKUGroupGuid;
            //                    newSku.Weight = topSku.Weight;
            //                    newSku.Sort = topSku.Sort;
            //                    newSku.ProductSKUNameGuid = topSku.ProductSKUNameGuid;
            //                    newSku.ProductSKUValueGuid = topSku.ProductSKUValueGuid;
            //                    var tempName = productSKUNameList.FirstOrDefault(c => c.ProductSKUNameGuid == topSku.ProductSKUNameGuid);
            //                    var tempValue = productSKUValueList.FirstOrDefault(c => c.ProductSKUValueGuid == topSku.ProductSKUValueGuid);
            //                    newSku.ProductSKUName = (tempName == null ? "-" : tempName.Name);
            //                    newSku.ProductSKUValue = (tempValue == null ? "-" : tempValue.ProductSKUValue);
            //                    newSku.EntityState = EntityStates.ToBeAdd;
            //                    addProductSKUSub.Add(newSku);
            //                }
            //            }
            //        }

            //        #endregion

            //    }
            //}

            //#region 批量提交
            //using (var tran = new SqlRTransaction())
            //{
            //    var queryPro = Factory.CreateT_BAS_Products(tran);
            //    var queryProCate = Factory.CreateT_BAS_ProductCategorys(tran);
            //    var queryProType = Factory.CreateT_BAS_ProductType(tran);
            //    var queryProSku = Factory.CreateT_BAS_ProductSKU(tran);
            //    tran.BeginTransaction();
            //    try
            //    {
            //        if (addProductListSub != null && addProductListSub.Count > 0)
            //        {
            //            queryPro.AddList(addProductListSub);
            //        }
            //        if (updateProductListSub != null && updateProductListSub.Count > 0)
            //        {
            //            queryPro.UpdateList(updateProductListSub);
            //        }
            //        if (addProductCategoryListSub != null && addProductCategoryListSub.Count > 0)
            //        {
            //            queryProCate.AddList(addProductCategoryListSub);
            //        }
            //        if (addProductTypeListSub != null && addProductTypeListSub.Count > 0)
            //        {
            //            queryProType.AddList(addProductTypeListSub);
            //        }

            //        if (deleteProductSKUSub != null && deleteProductSKUSub.Count > 0)
            //        {
            //            queryProSku.DeleteList(deleteProductSKUSub);
            //        }
            //        if (addProductSKUSub != null && addProductSKUSub.Count > 0)
            //        {
            //            queryProSku.AddList(addProductSKUSub);
            //        }

            //        tran.Commit();
            //        return new Result(true);
            //    }
            //    catch (Exception ex)
            //    {
            //        tran.Rollback();
            //        return new Result(false, "操作失败：" + ex.Message);
            //    }

            //}
            //#endregion
            
            #endregion
        }
        #endregion

        #region 同步分组商品
        /// <summary>
        /// 同步分组商品
        /// </summary>
        /// <param name="strArr"></param>
        /// <param name="checkNum">1-基本信息，2-售卖信息，3-全部（默认）</param>
        /// <returns></returns>
        public static Result ImportProductAgent(string strArr, int checkNum, bool includeCom)
        {
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            var agentProDisDets = js.Deserialize<Guid[]>(strArr);

            #region 商品信息库

            //需要导入/同步的代理
            List<T_BAS_ProductsWithAgentSub> agentProDisDetList = new List<T_BAS_ProductsWithAgentSub>();
            List<T_BAS_MerchantsAgent> merchantList = new List<T_BAS_MerchantsAgent>();

            //待导入/同步的商品相关信息
            List<T_BAS_Products> productList = new List<T_BAS_Products>();
            List<T_BAS_ProductCategorys> productCategoryList = new List<T_BAS_ProductCategorys>();
            List<T_BAS_ProductType> productTypeList = new List<T_BAS_ProductType>();
            List<T_BAS_ProductSKU> productSKUList = new List<T_BAS_ProductSKU>();
            List<T_BAS_ProductSKUName> productSKUNameList = new List<T_BAS_ProductSKUName>();
            List<T_BAS_ProductSKUValue> productSKUValueList = new List<T_BAS_ProductSKUValue>();

            //已选下级的商品相关信息
            List<T_BAS_Products> productListSub = new List<T_BAS_Products>();
            List<T_BAS_ProductCategorys> productCategoryListSub = new List<T_BAS_ProductCategorys>();
            List<T_BAS_ProductType> productTypeListSub = new List<T_BAS_ProductType>();
            List<T_BAS_ProductSKU> productSKUListSub = new List<T_BAS_ProductSKU>();
            List<T_BAS_ProductSKUName> productSKUNameListSub = new List<T_BAS_ProductSKUName>();
            List<T_BAS_ProductSKUValue> productSKUValueListSub = new List<T_BAS_ProductSKUValue>();

            //待添加/更新的商品相关信息
            List<T_BAS_Products> addProductListSub = new List<T_BAS_Products>();
            List<T_BAS_Products> updateProductListSub = new List<T_BAS_Products>();
            List<T_BAS_ProductCategorys> addProductCategoryListSub = new List<T_BAS_ProductCategorys>();
            List<T_BAS_ProductType> addProductTypeListSub = new List<T_BAS_ProductType>();
            List<T_BAS_ProductSKU> addProductSKUSub = new List<T_BAS_ProductSKU>();
            List<T_BAS_ProductSKU> deleteProductSKUSub = new List<T_BAS_ProductSKU>();
            #endregion


            #region 获取最新商品信息库
            using (var tran = new SqlRTransaction())
            {
                var queryProAgen = Factory.CreateT_BAS_ProductsWithAgentSub(tran);
                var queryMer = Factory.CreateT_BAS_MerchantsAgent(tran);
                var queryPro = Factory.CreateT_BAS_Products(tran);
                var queryProCate = Factory.CreateT_BAS_ProductCategorys(tran);
                var queryProType = Factory.CreateT_BAS_ProductType(tran);
                var queryProSku = Factory.CreateT_BAS_ProductSKU(tran);
                var queryProSkuName = Factory.CreateT_BAS_ProductSKUName(tran);
                var queryProSkuValue = Factory.CreateT_BAS_ProductSKUValue(tran);

                agentProDisDetList = queryProAgen.GetList(c => c.AgentProductDiscountDetailGuid.SqlIn(agentProDisDets));

                if (agentProDisDetList == null || agentProDisDetList.Count == 0)
                {
                    return new Result(false, "请选择需要操作的分组商品");
                }

                productList = queryPro.GetList(c => c.ProductGuid.SqlIn(agentProDisDetList.Select(d => d.ProductGuid.Value).ToArray()) && c.MerchantGuid == Common.CurrentManage.MerchantGuid);
                if (productList == null || productList.Count == 0)
                {
                    return new Result(false, "获取商品信息失败");
                }


                var errProduct = productList.FirstOrDefault(c => c.AgentPrice == null);
                if (errProduct != null)
                {
                    return new Result(false, string.Format("商品未添加代理统一价格：{0}", errProduct.ProductName));
                }
                merchantList = queryMer.GetList(c => c.FlagshipGroupGuid.SqlIn(agentProDisDetList.Select(d => d.FlagshipGroupGuid).ToArray()), isFilterMerchant: false);
                if (merchantList == null || merchantList.Count == 0)
                {
                    return new Result(false, "当前商品组无商家");
                }

                var cates = productList.Where(p => p.ProductCategoryGuid != null).Select(p => p.ProductCategoryGuid).ToArray();
                if (cates != null && cates.Count() > 0)
                {
                    productCategoryList = (queryProCate.GetList(c => c.ProductCategoryGuid.SqlIn(cates) && c.MerchantGuid == Common.CurrentManage.MerchantGuid) ?? new List<T_BAS_ProductCategorys>());
                }
                var types = productList.Where(p => p.ProductTypeGuid != null).Select(p => p.ProductTypeGuid.ToString()).ToArray();
                if (types != null && types.Count() > 0)
                {
                    productTypeList = (queryProType.GetList(c => c.ProductTypeGuid.SqlIn(types) && c.MerchantGuid == Common.CurrentManage.MerchantGuid) ?? new List<T_BAS_ProductType>());
                }

                productSKUList = (queryProSku.GetList(c => c.ProductGuid.SqlIn(productList.Select(p => p.ProductGuid).ToArray()) && c.MerchantGuid == Common.CurrentManage.MerchantGuid) ?? new List<T_BAS_ProductSKU>());


                if (productTypeList != null && productTypeList.Count > 0)
                {
                    productSKUNameList = (queryProSkuName.GetList(c => c.ProductTypeGuid.SqlIn(productTypeList.Select(t => t.ProductTypeGuid.ToString()).ToArray()) && c.MerchantGuid == Common.CurrentManage.MerchantGuid) ?? new List<T_BAS_ProductSKUName>());
                }
                if (productSKUNameList != null && productSKUNameList.Count > 0)
                {
                    productSKUValueList = (queryProSkuValue.GetList(c => c.ProductSKUNameGuid.SqlIn(productSKUNameList.Select(n => n.ProductSKUNameGuid.ToString()).ToArray()) && c.MerchantGuid == Common.CurrentManage.MerchantGuid) ?? new List<T_BAS_ProductSKUValue>());
                }



                var proGuids = productList.Select(p => p.ProductGuid.ToString()).ToArray();
                var merGuids = merchantList.Select(m => m.MerchantGuid.ToString()).ToArray();

                productListSub = (queryPro.GetList(c => c.MerchantGuid.SqlIn(merGuids) && c.OriginalProductGuid.SqlIn(proGuids), isFilterMerchant: false) ?? new List<T_BAS_Products>());
                productCategoryListSub = (queryProCate.GetList(c => c.MerchantGuid.SqlIn(merGuids), isFilterMerchant: false) ?? new List<T_BAS_ProductCategorys>());
                productTypeListSub = (queryProType.GetList(c => c.MerchantGuid.SqlIn(merGuids), isFilterMerchant: false) ?? new List<T_BAS_ProductType>());
                if (productListSub != null && productListSub.Count > 0)
                {
                    productSKUListSub = (queryProSku.GetList(c => c.MerchantGuid.SqlIn(merGuids) && c.ProductGuid.SqlIn(productListSub.Select(p => p.ProductGuid).ToArray()), isFilterMerchant: false) ?? new List<T_BAS_ProductSKU>());
                }
            }
            #endregion

            try
            {
                foreach (var agentProDisDet in agentProDisDetList)
                {
                    var subMerchants = merchantList.Where(c => c.FlagshipGroupGuid == agentProDisDet.FlagshipGroupGuid).ToList();
                    if (agentProDisDet.AgentProductDiscountGuid != null)
                    {
                        subMerchants = subMerchants.Where(c => c.AgentProductDiscountGuid == agentProDisDet.AgentProductDiscountGuid).ToList();
                    }
                    if (subMerchants == null || subMerchants.Count == 0)
                    {
                        continue;
                    }

                    foreach (var subMer in subMerchants)
                    {
                        var topPro = productList.FirstOrDefault(c => c.ProductGuid == agentProDisDet.ProductGuid);
                        if (topPro == null)
                        {
                            return new Result(false, "没有找到此商品");
                        }

                        #region 添加商品信息
                        var subProGuid = Guid.NewGuid();
                        var isNewProSub = true;
                        var subPro = productListSub.FirstOrDefault(c => c.OriginalProductGuid == topPro.ProductGuid && c.MerchantGuid == subMer.MerchantGuid);
                        if (subPro != null)
                        {
                            isNewProSub = false;
                            subProGuid = subPro.ProductGuid;
                        }

                        if (checkNum != 2)
                        {
                            #region 处理逻辑1
                            if (!isNewProSub)
                            {
                                subPro.EntityState = EntityStates.ToBeUpdated;
                                updateProductListSub.Add(subPro);

                                if (checkNum == 3)
                                {
                                    //价格信息
                                    subPro.Price = topPro.Price;
                                    subPro.MinPrice = decimal.Round((topPro.Price * (100 - agentProDisDet.MinPrice) / 100).Value, 2, MidpointRounding.AwayFromZero);
                                    subPro.MaxPrice = decimal.Round((topPro.Price * (100 + agentProDisDet.MaxPrice) / 100).Value, 2, MidpointRounding.AwayFromZero);
                                    subPro.MarketPrice = topPro.MarketPrice;
                                    subPro.AgentPrice = topPro.AgentPrice;
                                }

                                if (includeCom)
                                {
                                    //佣金信息
                                    //subPro.IsDefault = topPro.IsDefault;
                                    subPro.IsDefault = false;
                                    subPro.CommissionType = topPro.CommissionType;
                                    subPro.FirstCommission = topPro.FirstCommission;
                                    subPro.SecondCommission = topPro.SecondCommission;
                                    subPro.ThirdCommission = topPro.ThirdCommission;
                                    subPro.FirstCommissionAmount = topPro.FirstCommissionAmount;
                                    subPro.SecondCommissionAmount = topPro.SecondCommissionAmount;
                                    subPro.ThirdCommissionAmount = topPro.ThirdCommissionAmount;
                                }

                            }
                            else
                            {
                                subPro = new T_BAS_Products();
                                subPro.EntityState = EntityStates.ToBeAdd;
                                subPro.ProductGuid = subProGuid;
                                subPro.MerchantGuid = subMer.MerchantGuid;
                                subPro.SMerchantGuid = subMer.MerchantGuid;
                                addProductListSub.Add(subPro);

                                //价格信息
                                subPro.Price = topPro.Price;
                                subPro.MinPrice = decimal.Round((topPro.Price * (100 - agentProDisDet.MinPrice) / 100).Value, 2, MidpointRounding.AwayFromZero);
                                subPro.MaxPrice = decimal.Round((topPro.Price * (100 + agentProDisDet.MaxPrice) / 100).Value, 2, MidpointRounding.AwayFromZero);
                                subPro.MarketPrice = topPro.MarketPrice;
                                subPro.AgentPrice = topPro.AgentPrice;

                                //佣金信息 
                                //subPro.IsDefault = topPro.IsDefault;
                                subPro.IsDefault = false;
                                subPro.CommissionType = topPro.CommissionType;
                                subPro.FirstCommission = topPro.FirstCommission;
                                subPro.SecondCommission = topPro.SecondCommission;
                                subPro.ThirdCommission = topPro.ThirdCommission;
                                subPro.FirstCommissionAmount = topPro.FirstCommissionAmount;
                                subPro.SecondCommissionAmount = topPro.SecondCommissionAmount;
                                subPro.ThirdCommissionAmount = topPro.ThirdCommissionAmount;

                                //销量库存信息
                                subPro.InventoryWay = topPro.InventoryWay;
                                subPro.Inventory = topPro.Inventory;
                                subPro.Weight = topPro.Weight;
                                subPro.SalesVolume = 0;
                                subPro.BaseSalesVolume = topPro.BaseSalesVolume;


                                //运费模板
                                if (subMer.GoodsDeliveryType == AgentRuleConst.GoodsDeliveryType.总部)
                                {
                                    subPro.TemplatesGuid = topPro.TemplatesGuid;
                                } 
                                subPro.IsAgentsProduct = false;
                                subPro.IsPutaway = topPro.IsPutaway;
                                subPro.Recommend = topPro.Recommend;
                                subPro.Quota = topPro.Quota;
                                subPro.Sort = topPro.Sort;
                                subPro.IsProperty = topPro.IsProperty;
                                subPro.IsStandards = topPro.IsStandards;
                                subPro.PutawayDate = DateTime.Now;
                                subPro.OriginalProductGuid = topPro.ProductGuid;
                                subPro.AgentsIsPutaway = topPro.AgentsIsPutaway;
                                subPro.NoDelivery = topPro.NoDelivery;
                                subPro.NoReceive = topPro.NoReceive;
                                subPro.CategoryCode = topPro.CategoryCode;
                                subPro.ProductClassify = topPro.ProductClassify;

                                if (topPro.ProductCategoryGuid != null && topPro.ProductCategoryGuid != Guid.Empty)
                                {
                                    var subCate = productCategoryListSub.FirstOrDefault(c => c.OriginalProductCategoryGuid == topPro.ProductCategoryGuid && c.MerchantGuid == subMer.MerchantGuid);
                                    if (subCate == null)
                                    {
                                        subCate = addProductCategoryListSub.FirstOrDefault(c => c.OriginalProductCategoryGuid == topPro.ProductCategoryGuid && c.MerchantGuid == subMer.MerchantGuid);
                                    }
                                    if (subCate != null)
                                    {
                                        subPro.ProductCategoryGuid = subCate.ProductCategoryGuid;
                                    }
                                    else
                                    {
                                        var topCate = productCategoryList.FirstOrDefault(c => c.ProductCategoryGuid == topPro.ProductCategoryGuid);
                                        subCate = productCategoryListSub.FirstOrDefault(c => c.CategoryName == topCate.CategoryName && c.MerchantGuid == subMer.MerchantGuid);
                                        if (subCate != null)
                                        {
                                            subPro.ProductCategoryGuid = subCate.ProductCategoryGuid;
                                        }
                                        else
                                        {
                                            subPro.ProductCategoryGuid = Guid.NewGuid();
                                            var newCate = new T_BAS_ProductCategorys();
                                            newCate.MerchantGuid = subMer.MerchantGuid;
                                            newCate.SMerchantGuid = subMer.MerchantGuid;
                                            newCate.ProductCategoryGuid = subPro.ProductCategoryGuid;
                                            newCate.OriginalProductCategoryGuid = topCate.ProductCategoryGuid;
                                            newCate.Levels = topCate.Levels;
                                            newCate.ParentGuid = topCate.ParentGuid;
                                            newCate.Sort = topCate.Sort;
                                            newCate.CategoryCode = topCate.CategoryCode;
                                            newCate.CategoryName = topCate.CategoryName;
                                            newCate.Flag = topCate.Flag;
                                            newCate.Url = topCate.Url;
                                            newCate.EntityState = EntityStates.ToBeAdd;
                                            addProductCategoryListSub.Add(newCate);
                                        }
                                    }
                                }

                                if (topPro.ProductTypeGuid != null && topPro.ProductTypeGuid != Guid.Empty)
                                {
                                    var subType = productTypeListSub.FirstOrDefault(c => c.OriginalProductTypeGuid == topPro.ProductTypeGuid && c.MerchantGuid == subMer.MerchantGuid);
                                    if (subType == null)
                                    {
                                        subType = addProductTypeListSub.FirstOrDefault(c => c.OriginalProductTypeGuid == topPro.ProductTypeGuid && c.MerchantGuid == subMer.MerchantGuid);
                                    }
                                    if (subType != null)
                                    {
                                        subPro.ProductTypeGuid = subType.ProductTypeGuid;
                                    }
                                    else
                                    {
                                        var topType = productTypeList.FirstOrDefault(c => c.ProductTypeGuid == topPro.ProductTypeGuid);
                                        if (topType == null)
                                        {
                                            return new Result(false, string.Format("商品{0} 类型规格信息出现错误，请检查", topPro.ProductName));
                                        }
                                        subPro.ProductTypeGuid = Guid.NewGuid();
                                        var newType = new T_BAS_ProductType();
                                        newType.MerchantGuid = subMer.MerchantGuid;
                                        newType.SMerchantGuid = subMer.MerchantGuid;
                                        newType.OriginalProductTypeGuid = topType.ProductTypeGuid;
                                        newType.ProductTypeGuid = subPro.ProductTypeGuid.Value;
                                        newType.ProductTypeName = topType.ProductTypeName;
                                        newType.Remark = topType.Remark;
                                        newType.Sort = topType.Sort;
                                        newType.EntityState = EntityStates.ToBeAdd;
                                        addProductTypeListSub.Add(newType);
                                    }
                                }
                            }

                            //描述信息
                            subPro.ProductName = topPro.ProductName;
                            subPro.ProductCode = topPro.ProductCode;
                            subPro.ProductImage = topPro.ProductImage;
                            subPro.ProductImage1 = topPro.ProductImage1;
                            subPro.ProductImage2 = topPro.ProductImage2;
                            subPro.ProductImage3 = topPro.ProductImage3;
                            subPro.ProductImage4 = topPro.ProductImage4;
                            subPro.ProductImage5 = topPro.ProductImage5;
                            subPro.Description = topPro.Description;
                            subPro.ProductUrl = "http://" + subMer.UserID + string.Format(".shop.{0}/wxshop/productinfo?productsguid={1}", CurrentManage.DomainWxRoot, subPro.ProductGuid);
                            var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + RFrameGenerate.Common.RadomCode.DigitalCode(3) + ".png";
                            if (Common.QrCodeHelper.GenerationQrCode(subPro.ProductUrl, "", AppDomain.CurrentDomain.BaseDirectory + @"upload\qrcode\" + fileName))
                            {
                                subPro.QRCodeUrl = "/upload/qrcode/" + fileName;
                            }
                            #endregion

                        }
                        else if (checkNum == 2 && !isNewProSub)
                        {
                            #region 处理逻辑2
                            subPro.EntityState = EntityStates.ToBeUpdated;
                            updateProductListSub.Add(subPro);

                            //价格信息
                            subPro.Price = topPro.Price;
                            subPro.MinPrice = decimal.Round((topPro.Price * (100 - agentProDisDet.MinPrice) / 100).Value, 2, MidpointRounding.AwayFromZero);
                            subPro.MaxPrice = decimal.Round((topPro.Price * (100 + agentProDisDet.MaxPrice) / 100).Value, 2, MidpointRounding.AwayFromZero);
                            subPro.MarketPrice = topPro.MarketPrice;
                            subPro.AgentPrice = topPro.AgentPrice;

                            if (includeCom)
                            {
                                //佣金信息
                                //subPro.IsDefault = topPro.IsDefault;
                                subPro.IsDefault = false;
                                subPro.CommissionType = topPro.CommissionType;
                                subPro.FirstCommission = topPro.FirstCommission;
                                subPro.SecondCommission = topPro.SecondCommission;
                                subPro.ThirdCommission = topPro.ThirdCommission;
                                subPro.FirstCommissionAmount = topPro.FirstCommissionAmount;
                                subPro.SecondCommissionAmount = topPro.SecondCommissionAmount;
                                subPro.ThirdCommissionAmount = topPro.ThirdCommissionAmount;
                            }
                            #endregion
                        }

                        #endregion


                        if (checkNum == 3 || (checkNum == 1 && isNewProSub) || (checkNum == 2 && !isNewProSub))
                        {
                            #region 添加商品规格信息

                            var deleteSkus = productSKUListSub.Where(c => c.ProductGuid == subProGuid && c.MerchantGuid == subMer.MerchantGuid).ToList();
                            if (deleteSkus != null && deleteSkus.Count > 0)
                            {
                                deleteProductSKUSub.AddRange(deleteSkus);
                            }

                            var topSkus = productSKUList.Where(c => c.ProductGuid == topPro.ProductGuid);
                            if (topSkus != null && topSkus.Count() > 0)
                            {
                                foreach (var topSku in topSkus)
                                {
                                    var newSku = new T_BAS_ProductSKU();
                                    newSku.ProductSKUGuid = Guid.NewGuid();
                                    //newSku.AgentPrice = decimal.Round((topSku.AgentPrice * agentProDisDet.Discount / 100).Value, 2, 
                                    //MidpointRounding.AwayFromZero);
                                    newSku.AgentPrice = topSku.AgentPrice;
                                    newSku.Code = topSku.Code;
                                    newSku.Invenotory = topSku.Invenotory;
                                    newSku.OriginalProductSKUGuid = topSku.ProductSKUGuid;
                                    newSku.Price = topSku.Price;
                                    newSku.PriceMin = decimal.Round((topSku.Price * (100 - agentProDisDet.MinPrice) / 100).Value, 2, MidpointRounding.AwayFromZero);
                                    newSku.PriceMax = decimal.Round((topSku.Price * (100 + agentProDisDet.MaxPrice) / 100).Value, 2, MidpointRounding.AwayFromZero);
                                    newSku.ProductGuid = subPro.ProductGuid;
                                    newSku.ProductSKUGroupGuid = topSku.ProductSKUGroupGuid;
                                    newSku.Weight = topSku.Weight;
                                    newSku.Sort = topSku.Sort;
                                    newSku.ProductSKUNameGuid = topSku.ProductSKUNameGuid;
                                    newSku.ProductSKUValueGuid = topSku.ProductSKUValueGuid;
                                    var tempName = productSKUNameList.FirstOrDefault(c => c.ProductSKUNameGuid == topSku.ProductSKUNameGuid);
                                    var tempValue = productSKUValueList.FirstOrDefault(c => c.ProductSKUValueGuid == topSku.ProductSKUValueGuid);
                                    newSku.ProductSKUName = (tempName == null ? "-" : tempName.Name);
                                    newSku.ProductSKUValue = (tempValue == null ? "-" : tempValue.ProductSKUValue);
                                    newSku.EntityState = EntityStates.ToBeAdd;
                                    newSku.MerchantGuid = subMer.MerchantGuid;
                                    newSku.SMerchantGuid = subMer.MerchantGuid;
                                    addProductSKUSub.Add(newSku);
                                }
                            }

                            #endregion


                        }


                    }
                }
            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log(string.Format("ImportProductAgent读取商品失败！商家GUID：{0},错误信息：{1}", CurrentManage.MerchantGuid, ex.ToString()));
                return new Result(false, "服务器繁忙(READ)，可逐个同步或者稍后尝试");
            }

            #region 批量提交
            using (var tran = new SqlRTransaction())
            {
                var queryPro = Factory.CreateT_BAS_Products(tran);
                var queryProCate = Factory.CreateT_BAS_ProductCategorys(tran);
                var queryProType = Factory.CreateT_BAS_ProductType(tran);
                var queryProSku = Factory.CreateT_BAS_ProductSKU(tran);
                tran.BeginTransaction();
                try
                {
                    if (addProductListSub != null && addProductListSub.Count > 0)
                    {
                        queryPro.AddList(addProductListSub);
                    }
                    if (updateProductListSub != null && updateProductListSub.Count > 0)
                    {
                        queryPro.UpdateList(updateProductListSub);
                    }
                    if (addProductCategoryListSub != null && addProductCategoryListSub.Count > 0)
                    {
                        queryProCate.AddList(addProductCategoryListSub);
                    }
                    if (addProductTypeListSub != null && addProductTypeListSub.Count > 0)
                    {
                        queryProType.AddList(addProductTypeListSub);
                    }

                    if (deleteProductSKUSub != null && deleteProductSKUSub.Count > 0)
                    {
                        queryProSku.DeleteList(deleteProductSKUSub);
                    }
                    if (addProductSKUSub != null && addProductSKUSub.Count > 0)
                    {
                        queryProSku.AddList(addProductSKUSub);
                    }

                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    Wechat.LogManage.Log(string.Format("ImportProductAgent批量写入失败！商家GUID：{0},错误信息：{1}", CurrentManage.MerchantGuid, ex.ToString()));
                    return new Result(false, "服务器繁忙(Write)，可逐个同步或者稍后尝试");
                }

            }
            #endregion

        }
        #endregion



    }

}
