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

namespace RFrameGenerate.BLL.Products
{
    public class ProductsManage
    {
        public static List<T_BAS_Products> GetPageList(GridModel gridModel, string name, Guid? ptid)
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                return query.GetPageList(gridModel, a => a.ProductName.SqlLike(name) && a.ProductCategoryGuid == ptid && a.MerchantGuid == Common.CurrentManage.MerchantGuid, true, p => p.ProductCode, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
            }
        }

        public static Result SaveChangeEntity(T_BAS_Products entity, List<T_BAS_ProductSKU> list)
        {
            if (RFrameGenerate.Common.CurrentManage.MerchantType == DictionaryConst.Versionb.Basic && (entity.Price == 0 || entity.MinPrice == 0 || entity.MaxPrice == 0 || entity.MarketPrice == 0 || entity.AgentPrice == 0))
            {
                return new Result(false, "基础版不能设置商品价格为0元！");
            }

            if (entity == null) return new Result(false, "保存对象不能为空！");

            if (entity.TemplatesGuid == null)
            {
                var defaultTemplete = RFrameGenerate.BLL.Logistics.TemplatesManage.CurrentTemplates();
                if (defaultTemplete != null) entity.TemplatesGuid = defaultTemplete.TemplatesGuid;
            }
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_Products(tran);
                var query_sku = Factory.CreateT_BAS_ProductSKU(tran);
                var merchants = MerchantManage.GetEntity(Common.CurrentManage.MerchantGuid);
                if (merchants == null)
                {
                    return new Result(false, "没有找到该商家！");
                }

                entity.ProductUrl = "http://" + merchants.UserID + string.Format(".shop.{0}/wxshop/productinfo?productsguid={1}", CurrentManage.DomainWxRoot, entity.ProductGuid);
                string basePath = AppDomain.CurrentDomain.BaseDirectory + @"upload\qrcode\";

                var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + RadomCode.DigitalCode(3) + ".png";
                var srcEntity = query.GetFirstData(p => p.ProductGuid == entity.ProductGuid && p.MerchantGuid == Common.CurrentManage.MerchantGuid, false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                if (srcEntity != null && string.IsNullOrEmpty(srcEntity.QRCodeUrl) != true)
                    fileName = srcEntity.QRCodeUrl.Replace("/upload/qrcode/", string.Empty);

                if (Common.QrCodeHelper.GenerationQrCode(entity.ProductUrl, "", basePath + fileName))
                {
                    entity.QRCodeUrl = "/upload/qrcode/" + fileName;
                }
                if (entity.IsDefault == true)
                {
                    entity.FirstCommission = decimal.Parse(ParameterManage.GetParameterByName(ParameterName.CommissionMember.FirstCommission)) / 100;
                    entity.SecondCommission = decimal.Parse(ParameterManage.GetParameterByName(ParameterName.CommissionMember.SecondCommission)) / 100;
                    entity.ThirdCommission = decimal.Parse(ParameterManage.GetParameterByName(ParameterName.CommissionMember.ThirdCommission)) / 100;
                }
                try
                {

                    tran.BeginTransaction();
                    if (srcEntity == null)
                    {
                        if (entity.IsPutaway)
                        {
                            entity.PutawayDate = DateTime.Now;
                        }
                        if (entity.IsStandards)
                        {
                            if (list == null || list.Count == 0) return new Result(false, "商品规格不能为空！");
                            query_sku.AddList(list);
                        }
                        query.Add(entity);
                    }
                    //更新
                    else
                    {
                        entity.ProductGuid = srcEntity.ProductGuid;
                        entity.AgentsIsPutaway = srcEntity.AgentsIsPutaway;
                        entity.MinPrice = srcEntity.MinPrice;
                        entity.MaxPrice = srcEntity.MaxPrice;
                        entity.OriginalProductGuid = srcEntity.OriginalProductGuid;
                        entity.IsAgentsProduct = srcEntity.IsAgentsProduct;

                        query.Delete(a => a.ProductGuid == srcEntity.ProductGuid && a.MerchantGuid == Common.CurrentManage.MerchantGuid, false);
                        query.Add(entity);


                        if (entity.IsStandards)
                        {
                            if (list == null || list.Count == 0) return new Result(false, "商品规格不能为空！");

                            query_sku.Delete(a => a.ProductGuid == srcEntity.ProductGuid && a.MerchantGuid == Common.CurrentManage.MerchantGuid, false);
                            query_sku.AddList(list);
                        }
                    }
                    tran.Commit();
                    return new Result(true);
                }
                catch (Exception err)
                {
                    tran.Rollback();
                    return new Result(false, err.Message);
                }
            }

        }

        public static Result SaveChangeEntitySub(T_BAS_Products entity, string skuArr)
        {
            using (var tran = new SqlRTransaction())
            {
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                var proSkus = js.Deserialize<List<PT_BAS_ProductSKUSub>>(skuArr);
                var query = Factory.CreateT_BAS_Products(tran);
                var query_sku = Factory.CreateT_BAS_ProductSKU(tran);
                var merchants = MerchantManage.GetEntity(Common.CurrentManage.MerchantGuid);
                if (merchants == null)
                {
                    return new Result(false, "没有找到该商家！");
                }

                entity.ProductUrl = "http://" + merchants.UserID + string.Format(".shop.{0}/wxshop/productinfo?productsguid={1}", CurrentManage.DomainWxRoot, entity.ProductGuid);
                string basePath = AppDomain.CurrentDomain.BaseDirectory + @"upload\qrcode\";

                var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + RadomCode.DigitalCode(3) + ".png";

                if (Common.QrCodeHelper.GenerationQrCode(entity.ProductUrl, "", basePath + fileName))
                {
                    entity.QRCodeUrl = "/upload/qrcode/" + fileName;
                }
                if (entity.IsDefault == true)
                {
                    entity.FirstCommission = decimal.Parse(ParameterManage.GetParameterByName(ParameterName.CommissionMember.FirstCommission)) / 100;
                    entity.SecondCommission = decimal.Parse(ParameterManage.GetParameterByName(ParameterName.CommissionMember.SecondCommission)) / 100;
                    entity.ThirdCommission = decimal.Parse(ParameterManage.GetParameterByName(ParameterName.CommissionMember.ThirdCommission)) / 100;
                }
                var srcEntity = query.GetFirstData(p => p.ProductGuid == entity.ProductGuid && p.MerchantGuid == Common.CurrentManage.MerchantGuid, false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                try
                {

                    tran.BeginTransaction();

                    entity.ProductGuid = srcEntity.ProductGuid;
                    entity.AgentsIsPutaway = srcEntity.AgentsIsPutaway;
                    entity.MinPrice = srcEntity.MinPrice;
                    entity.MaxPrice = srcEntity.MaxPrice;
                    if (entity.Price > entity.MaxPrice || entity.Price < entity.MinPrice)
                    {
                        throw new Exception(string.Format("价格超出合法范围({0}-{1})", entity.MinPrice, entity.MaxPrice));
                    }
                    entity.OriginalProductGuid = srcEntity.OriginalProductGuid;
                    entity.IsAgentsProduct = srcEntity.IsAgentsProduct;
                    entity.AgentPrice = srcEntity.AgentPrice;
                    query.Delete(a => a.ProductGuid == srcEntity.ProductGuid && a.MerchantGuid == Common.CurrentManage.MerchantGuid, false);
                    query.Add(entity);


                    if (entity.IsStandards)
                    {
                        if (proSkus == null || proSkus.Count == 0) return new Result(false, "商品规格不能为空！");

                        //修正规格数据 Bing
                        var skulist = query_sku.GetList(c => c.ProductGuid == srcEntity.ProductGuid && c.MerchantGuid == Common.CurrentManage.MerchantGuid);
                        skulist.ForEach(c =>
                        {
                            var temp = proSkus.First(s => s.GroupGuid == c.ProductSKUGroupGuid);
                            c.Price = temp.Price;
                            if (c.Price > c.PriceMax || c.Price < c.PriceMin)
                            {
                                throw new Exception(string.Format("价格明细超出合法范围({0}-{1})", c.PriceMin, c.PriceMax));
                            }
                            c.Invenotory = temp.Inventory;
                            c.Code = temp.ProductCode;
                            c.Weight = temp.Weight;
                            c.EntityState = EntityStates.ToBeUpdated;

                        });
                        query_sku.UpdateList(skulist);

                    }

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

        }

        /// <summary>
        /// 根据GUID删除数据
        /// </summary>
        public static Result DeleteEntity(Guid entityGuid, ref List<T_BAS_Products> relList)
        {
            if (entityGuid == Guid.Empty) return new Result(false, "没有数据删除！");

            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_Products(tran);
                var query_sku = Factory.CreateT_BAS_ProductSKU(tran);
                var query_productAgentGroPro = Factory.CreateT_BAS_ProductsWithAgentSub(tran);
                var model = query.GetFirstData(p => p.ProductGuid == entityGuid && p.MerchantGuid == Common.CurrentManage.MerchantGuid, false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);

                if (model == null) return new Result(false, "没有数据删除！");

                if (model.IsAgentsProduct == true) return new Result(false, "此商品为代理中商品，请在供货管理处删除！");
                var isAgentGroProquery = query_productAgentGroPro.GetCount(c => c.ProductGuid == entityGuid);
                if (isAgentGroProquery > 0) return new Result(false, "此商品为代理分组商品，请在供货管理处删除！");

                model.EntityState = EntityStates.ToBeDelete;

                relList.Add(model);
                tran.BeginTransaction();
                try
                {
                    query.DeleteList(relList);
                    if (model.IsStandards)
                    {
                        query_sku.Delete(a => a.ProductGuid == model.ProductGuid && a.MerchantGuid == Common.CurrentManage.MerchantGuid, false);
                    }
                    tran.Commit();
                }
                catch (Exception err)
                {
                    tran.Rollback();
                    return new Result(false, err.Message);
                }

            }
            return new Result(true);

        }

        public static Result GetEntity(Guid guid, bool shelves)
        {
            try
            {
                using (var query = Factory.CreateT_BAS_Products())
                {
                    var model = query.GetFirstData(p => p.ProductGuid == guid && p.MerchantGuid == Common.CurrentManage.MerchantGuid, false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);

                    if (model == null) return new Result(false, "找不到该商品！");

                    query.Update(m => new object[] {
                        m.IsPutaway==shelves,
                        m.PutawayDate==DateTime.Now
                    }, m => m.ProductGuid == guid && m.MerchantGuid == Common.CurrentManage.MerchantGuid, false);
                }

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

        public static T_BAS_Products GetEntity(Guid guid)
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                return query.GetFirstData(p => p.MerchantGuid == Common.CurrentManage.MerchantGuid && p.ProductGuid == guid, isFilterMerchant: false);
            }
        }

        public static Result GetQRCode(Guid guid, ref string srcQRCode)
        {
            try
            {
                using (var query = Factory.CreateT_BAS_Products())
                {
                    var model = query.GetFirstData(p => p.ProductGuid == guid && p.MerchantGuid == Common.CurrentManage.MerchantGuid, false, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);

                    if (model == null) return new Result(false, "找不到该商品！");

                    if (string.IsNullOrEmpty(model.QRCodeUrl)) return new Result(false, "该商品没有上传二维码！");

                    srcQRCode = model.QRCodeUrl;
                }

            }
            catch (Exception err)
            {

                new Result(false, err.Message);
            }
            return new Result(true);
        }

        public static List<T_BAS_Products> GetProductList(List<OrderConfirm> list)
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                Guid[] ids = list.Select(a => a.id).ToArray();
                return query.GetList(a => a.ProductGuid.SqlIn(ids), isFilterMerchant: false);
            }
        }

        public static List<T_BAS_Products> GetList()
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                var list = query.GetList(c => c.IsPutaway == true && c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid, false, b => b.Sort, DAL.Enums.OrderMethods.DESC, RFramework.SQLServer.Enums.LockType.Default, false);
                return list;
            }
        }

        public static List<T_BAS_Products> GetAllList()
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                return query.GetList(c => c.IsPutaway == true && c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid, isFilterMerchant: false);
            }
        }
        //获取所有商品（不分商家，维护用）
        public static List<T_BAS_Products> GetListAll()
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                return query.GetList(null, false, null, OrderMethods.Default, LockType.Default, false);
            }
        }

        public static List<T_BAS_Products> GetPageListByCurrentMerchan(GridModel gridModel, string productName, Guid? categoryGuid, bool isAgent)
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                Expression<Func<T_BAS_Products, bool>> exp = c => c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid;

                if (isAgent) exp = exp.AndAlso(c => c.IsAgentsProduct == isAgent);
                else exp = exp.AndAlso(c => c.IsAgentsProduct == isAgent || c.IsAgentsProduct.SqlIsNull());

                if (!string.IsNullOrEmpty(productName))
                {
                    exp = exp.AndAlso(c => c.ProductName.SqlLike(productName));
                }
                if (categoryGuid != null)
                {
                    exp = exp.AndAlso(c => c.ProductCategoryGuid == categoryGuid);
                }
                return query.GetPageList(gridModel, exp, false, s => s.Sort, DAL.Enums.OrderMethods.DESC);
            }
        }
        /// <summary>
        /// 删除代理商品
        /// </summary>
        /// <param name="productGuid"></param>
        /// <returns></returns>
        public static Result DeleteAgentProduct(Guid productGuid)
        {
            using (var trans = new SqlRTransaction())
            {
                trans.BeginTransaction();
                var query = Factory.CreateT_BAS_Products(trans);
                var query_sku = Factory.CreateT_BAS_ProductSKU(trans);

                var model = query.GetDataByGuid(productGuid);

                if (model == null) return new Result(false, "商品不存在或已被删除！");

                query.Update(m => new object[] { m.IsAgentsProduct == false }, c => c.ProductGuid == productGuid && c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);

                var guids = AgentsFlagshipManage.GetSubMerchantList().Select(m => m.MerchantGuid).ToArray();

                var listProduct = query.GetList(a => a.MerchantGuid.SqlIn(guids) && a.OriginalProductGuid == productGuid, false);
                //if (listProduct.Count == 0) return new Result(false, "代理中的商品不存在或已被删除！");

                //删除商品规格
                var productGuids = listProduct.Select(a => a.ProductGuid).ToArray();
                if (productGuids.Length > 0)
                {
                    query_sku.Delete(a => a.ProductGuid.SqlIn(productGuids) && a.MerchantGuid.SqlIn(guids), isFilterMerchant: false);
                }
                query.Delete(a => a.MerchantGuid.SqlIn(guids) && a.OriginalProductGuid == productGuid, false);
                trans.Commit();
                query.Dispose();
            }
            return new Result(true);
        }

        public static Result HandleAgentProduct(Guid productGuid)
        {
            using (var trans = new SqlRTransaction())
            {
                trans.BeginTransaction();

                var query = Factory.CreateT_BAS_Products(trans);
                var model = query.GetDataByGuid(productGuid);

                if (model == null) return new Result(false, "商品不存在或已被删除！");

                bool flag = model.AgentsIsPutaway.HasValue && model.AgentsIsPutaway.Value ? false : true;

                query.Update(m => new object[] { m.AgentsIsPutaway == flag }, c => c.ProductGuid == productGuid && c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);

                var guids = AgentsFlagshipManage.GetSubMerchantList().Select(m => m.MerchantGuid).ToArray();

                if (guids.Length <= 0) return new Result(false, "该商品还没有代理商！");

                foreach (var item in guids)
                {
                    query.Update(m => new object[] { m.IsPutaway == flag }, m => m.MerchantGuid == item.Value && m.OriginalProductGuid == productGuid, false);
                }

                trans.Commit();
                query.Dispose();

            }
            return new Result(true);
        }

        //public static Result UpdateAgentProduct(Guid productGuid, string flag)
        //{
        //    using (var query = Factory.CreateT_BAS_Products())
        //    {
        //        var model = query.GetDataByGuid(productGuid);

        //        if (model == null) return new Result(false, "商品不存在或已被删除！");

        //        var guids = AgentsFlagshipManage.GetSubMerchantList().Select(m => m.MerchantGuid).ToArray();

        //        if (guids.Length <= 0) return new Result(false, "该商品还没有代理商！");

        //        foreach (var item in guids)
        //        {
        //            var entity = query.GetFirstData(c => c.OriginalProductGuid == productGuid && c.MerchantGuid == item.Value,false,null,OrderMethods.Default,LockType.Default,false);
        //            if (flag == "0" && entity != null)
        //            {                    
        //                entity.ProductName = model.ProductName;
        //                entity.ProductUrl = model.ProductUrl;
        //                entity.QRCodeUrl = model.QRCodeUrl;
        //                entity.ProductImage = model.ProductImage;
        //                entity.ProductImage1 = model.ProductImage1;
        //                entity.ProductImage2 = model.ProductImage2;
        //                entity.ProductImage3 = model.ProductImage3;
        //                entity.ProductImage4 = model.ProductImage4;
        //                entity.ProductImage5 = model.ProductImage5;
        //                entity.Description = model.Description;
        //                entity.ProductCode = model.ProductCode;
        //                entity.Inventory = model.Inventory;
        //                entity.Weight = model.Weight;
        //                entity.SalesVolume = model.SalesVolume;
        //                entity.MarketPrice = model.MarketPrice;
        //                entity.Price = model.Price;

        //                query.Delete(entity.ProductGuid); 
        //                query.Add(entity);
        //            }
        //            else if (flag == "1" && entity != null)
        //            {
        //                entity.ProductName = model.ProductName;
        //                entity.ProductUrl = model.ProductUrl;
        //                entity.QRCodeUrl = model.QRCodeUrl;
        //                entity.ProductImage = model.ProductImage;
        //                entity.ProductImage1 = model.ProductImage1;
        //                entity.ProductImage2 = model.ProductImage2;
        //                entity.ProductImage3 = model.ProductImage3;
        //                entity.ProductImage4 = model.ProductImage4;
        //                entity.ProductImage5 = model.ProductImage5;
        //                entity.Description = model.Description;
        //                entity.ProductCode = model.ProductCode;

        //                query.Delete(entity.ProductGuid);
        //                query.Add(entity);
        //            }
        //            else if (flag == "2" && entity != null)
        //            {
        //                entity.Inventory = model.Inventory;
        //                entity.Weight = model.Weight;
        //                entity.SalesVolume = model.SalesVolume;
        //                entity.MarketPrice = model.MarketPrice;
        //                entity.Price = model.Price;

        //                query.Delete(entity.ProductGuid);
        //                query.Add(entity);
        //            }
        //        }

        //    }
        //    return new Result(true);
        //}
        /// <summary>
        /// 同步商品分类
        /// </summary>
        /// <returns></returns>
        public static Result UpdateCategory()
        {
            using (var queryProductCategory = Factory.CreateT_BAS_ProductCategorys())
            {
                try
                {
                    var guids = AgentsFlagshipManage.GetSubMerchantList().Select(m => m.MerchantGuid).ToArray();
                    var topType = queryProductCategory.GetList(a => a.MerchantGuid == Common.CurrentManage.MerchantGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                    foreach (var guid in guids)
                    {
                        if (topType.Count > 0)
                        {
                            List<T_BAS_ProductCategorys> lstType = new List<T_BAS_ProductCategorys>();
                            List<T_BAS_ProductCategorys> addList = 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 = guid;
                                entity.Sort = item.Sort;
                                entity.Url = item.Url;
                                if (item.ParentGuid != null)
                                {
                                    var model = addList.FirstOrDefault(a => a.OriginalProductCategoryGuid == item.ParentGuid && a.MerchantGuid == guid);
                                    if (model != null) entity.ParentGuid = model.ProductCategoryGuid;
                                }
                                var model_category = addList.FirstOrDefault(a => a.MerchantGuid == guid && 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);
                            }
                        }
                    }
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }
            }
        }

        /// <summary>
        /// 同步商品
        /// </summary>
        /// <param name="productGuid"></param>
        /// <param name="flag">0：:全部 1：同步商品 2：同步规格 </param>
        /// <returns></returns>
        public static Result UpdateAgentProduct(Guid productGuid, string flag)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_BAS_Products(tran);
                var model = query.GetDataByGuid(productGuid);
                if (model == null) return new Result(false, "商品不存在或已被删除！");

                var guids = AgentsFlagshipManage.GetSubMerchantList().Select(m => m.MerchantGuid).ToArray();
                if (guids.Length <= 0) return new Result(false, "该商品还没有代理商！");

                try
                {
                    tran.BeginTransaction();

                    if (flag == "0")
                    {
                        query.Update(m => new object[] { 
                            m.ProductName == model.ProductName,
                            m.ProductUrl == model.ProductUrl,
                            m.QRCodeUrl == model.QRCodeUrl,
                            m.ProductImage == model.ProductImage,
                            m.ProductImage1 == model.ProductImage1,
                            m.ProductImage2 == model.ProductImage2,
                            m.ProductImage3 == model.ProductImage3,
                            m.ProductImage4 == model.ProductImage4,
                            m.ProductImage5 == model.ProductImage5,
                            m.Description == model.Description,
                            m.ProductCode == model.ProductCode,
                            m.Inventory == model.Inventory,
                            m.Weight == model.Weight,
                            m.SalesVolume == model.SalesVolume,
                            m.MarketPrice == model.MarketPrice,
                            m.Price == model.Price,
                        }, c => c.OriginalProductGuid == productGuid && c.MerchantGuid.SqlIn(guids), false);

                    }
                    else if (flag == "1")
                    {
                        query.Update(m => new object[] { 
                            m.ProductName == model.ProductName,
                            m.ProductUrl == model.ProductUrl,
                            m.QRCodeUrl == model.QRCodeUrl,
                            m.ProductImage == model.ProductImage,
                            m.ProductImage1 == model.ProductImage1,
                            m.ProductImage2 == model.ProductImage2,
                            m.ProductImage3 == model.ProductImage3,
                            m.ProductImage4 == model.ProductImage4,
                            m.ProductImage5 == model.ProductImage5,
                            m.Description == model.Description,
                            m.ProductCode == model.ProductCode,
                        }, c => c.OriginalProductGuid == productGuid && c.MerchantGuid.SqlIn(guids), false);

                    }
                    else if (flag == "2")
                    {
                        query.Update(m => new object[] { 
                            m.Inventory == model.Inventory,
                            m.Weight == model.Weight,
                            m.SalesVolume == model.SalesVolume,
                            m.MarketPrice == model.MarketPrice,
                            m.Price == model.Price,
                        }, c => c.OriginalProductGuid == productGuid && c.MerchantGuid.SqlIn(guids), false);
                    }

                    if (flag == "0" || flag == "2")
                    {
                        #region 同步商品规格
                        var query_sku = Factory.CreateT_BAS_ProductSKU(tran);
                        var query_skuName = Factory.CreateT_BAS_ProductSKUName(tran);
                        var query_skuValue = Factory.CreateT_BAS_ProductSKUValue(tran);
                        var query_productType = Factory.CreateT_BAS_ProductType(tran);
                        var query_merchant = Factory.CreateT_BAS_Merchants(tran);

                        var merchantList = query_merchant.GetList(m => m.MerchantGuid.SqlIn(guids.Select(c => c.Value).ToArray()), isFilterMerchant: false);


                        //当前商品规格数据
                        var listTopSKU = query_sku.GetList(a => a.ProductGuid == productGuid && a.MerchantGuid == Common.CurrentManage.MerchantGuid, isFilterMerchant: false);
                        if (listTopSKU == null || listTopSKU.Count == 0)
                        {
                            tran.Rollback();
                            return new Result(false, "当前商品规格获取失败");
                        }

                        //所有下级的对应当前商品数据
                        var currGuids = merchantList.Select(c => c.MerchantGuid).ToList();
                        var newGuids = new List<Guid?>();
                        currGuids.ForEach(c =>
                        {
                            newGuids.Add(c);
                        });
                        guids = newGuids.ToArray();

                        var productList = query.GetList(c => c.OriginalProductGuid == productGuid && c.MerchantGuid.SqlIn(guids), isFilterMerchant: false);
                        var typeList = query_productType.GetList(c => c.OriginalProductTypeGuid == model.ProductTypeGuid && c.MerchantGuid.SqlIn(guids), isFilterMerchant: false);
                        if (typeList == null & typeList.Count <= 0)
                        {
                            tran.Rollback();
                            return new Result(false, "当前商品类型数据异常");
                        }
                        var skunameList = query_skuName.GetList(c => c.MerchantGuid.SqlIn(guids) && c.ProductTypeGuid.SqlIn(typeList.Select(t => t.ProductTypeGuid.ToString()).ToArray()), isFilterMerchant: false);
                        if (skunameList == null & skunameList.Count <= 0)
                        {
                            tran.Rollback();
                            return new Result(false, "当前规格数据异常");
                        }
                        var skuvalueList = query_skuValue.GetList(c => c.MerchantGuid.SqlIn(guids) && c.ProductSKUNameGuid.SqlIn(skunameList.Select(n => n.ProductSKUNameGuid.ToString()).ToArray()), isFilterMerchant: false);
                        if (skunameList == null & skunameList.Count <= 0)
                        {
                            tran.Rollback();
                            return new Result(false, "当前规格数据异常");
                        }

                        //清空规格
                        query_sku.Delete(a => a.ProductGuid.SqlIn(productList.Select(c => c.ProductGuid).ToArray()), isFilterMerchant: false);

                        var newskuList = new List<T_BAS_ProductSKU>();
                        foreach (var guid in guids)
                        {
                            //新增规格
                            foreach (var item in listTopSKU)
                            {
                                var product = productList.FirstOrDefault(a => a.MerchantGuid == guid);

                                var skuname = skunameList.FirstOrDefault(a => a.OriginalProductSKUNameGuid == item.ProductSKUNameGuid && a.MerchantGuid == guid);
                                var skuvalue = skuvalueList.FirstOrDefault(a => a.OriginalProductSKUValueGuid == item.ProductSKUValueGuid && a.MerchantGuid == guid);
                                if (skuname == null || skuvalue == null)
                                {
                                    continue;
                                }
                                T_BAS_ProductSKU sku = new T_BAS_ProductSKU()
                                {
                                    ProductSKUGuid = Guid.NewGuid(),
                                    ProductGuid = product.ProductGuid,
                                    ProductSKUNameGuid = (skuname.ProductSKUNameGuid),
                                    ProductSKUValueGuid = (skuvalue.ProductSKUValueGuid),
                                    MerchantGuid = guid,
                                    ProductSKUGroupGuid = item.ProductSKUGroupGuid,
                                    Price = item.Price,
                                    Invenotory = item.Invenotory,
                                    Code = item.Code,
                                    Weight = item.Weight,
                                    Sort = item.Sort,
                                    OriginalProductSKUGuid = item.ProductSKUGuid,
                                    SMerchantGuid = guid,
                                    EntityState = EntityStates.ToBeAdd
                                };

                                newskuList.Add(sku);
                            }

                            var productType = typeList.FirstOrDefault(a => a.MerchantGuid == guid);
                            if (productType == null)
                            {
                                tran.Rollback();
                                return new Result(false, "操作失败，类型数据异常");
                            }
                            else
                            {
                                productList.ForEach(c =>
                                {
                                    c.ProductTypeGuid = productType.ProductTypeGuid;
                                    c.EntityState = EntityStates.ToBeUpdated;
                                });
                            }
                        }

                        query.UpdateList(productList);

                        if (newskuList.Count > 0)
                        {
                            query_sku.AddList(newskuList);

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

        }

        /// <summary>
        /// 导入商品到下级代理
        /// </summary>
        /// <param name="productGuid"></param>
        /// <param name="minPrice"></param>
        /// <param name="maxPrice"></param>
        /// <returns></returns>
        public static Result ImportAgentProduct(Guid productGuid, decimal? minPrice, decimal? maxPrice)
        {
            using (var trans = new SqlRTransaction())
            {
                Result result = new Result(true);
                var query = Factory.CreateT_BAS_Products(trans);
                var categoryQuery = Factory.CreateT_BAS_ProductCategorys(trans);
                var typeQuery = Factory.CreateT_BAS_ProductType(trans);
                var query_sku = Factory.CreateT_BAS_ProductSKU(trans);
                var query_merchant = Factory.CreateT_BAS_Merchants(trans);
                var model = query.GetDataByGuid(productGuid);
                if (model == null) return new Result(false, "商品不存在或已被删除！");

                var guids = AgentsFlagshipManage.GetSubMerchantList().Select(m => m.MerchantGuid).ToArray();
                var merchantList = query_merchant.GetList(m => m.MerchantGuid.SqlIn(guids.Select(c => c.Value).ToArray()), isFilterMerchant: false);
                var newGuids = new List<Guid?>();
                var currGuids = merchantList.Select(c => c.MerchantGuid).ToList();
                currGuids.ForEach(c =>
                {
                    newGuids.Add(c);
                });
                guids = newGuids.ToArray();

                if (guids.Length == 0) return new Result(false, "找不到代理商！");
                var list = new List<T_BAS_Products>();

                var category = categoryQuery.GetDataByGuid(model.ProductCategoryGuid);
                if (category == null) return new Result(false, "找不到商品分类！");

                //检查商品类型、商品分类是否存在
                bool isExist = IsExistCateGory(guids, category.CategoryName, categoryQuery);
                if (!isExist) return new Result(false, "请先导入同步商品分类！");

                isExist = isExistType(guids, typeQuery);
                if (!isExist) return new Result(false, "请先导入同步商品类型！");

                string basePath = AppDomain.CurrentDomain.BaseDirectory + @"upload\qrcode\";

                //代理本地数据补充 Bing

                var categoryList = categoryQuery.GetList(c => c.MerchantGuid.SqlIn(guids), isFilterMerchant: false);

                var typeList = typeQuery.GetList(c => c.MerchantGuid.SqlIn(guids), isFilterMerchant: false);


                foreach (var item in guids)
                {
                    var tempGuid = Guid.NewGuid();
                    var entity = new T_BAS_Products();
                    var merchant = merchantList.FirstOrDefault(a => a.MerchantGuid == item);

                    var categories = categoryList.Where(m => m.MerchantGuid == item).ToList();

                    var ProductCategoryGuid = Guid.Empty;
                    if (category != null)
                    {
                        if (categories.Exists(m => m.CategoryName == category.CategoryName))
                        {
                            ProductCategoryGuid = categories.FirstOrDefault(m => m.CategoryName == category.CategoryName).ProductCategoryGuid;
                        }
                        else
                        {
                            ProductCategoryGuid = Guid.NewGuid();
                            //if (ProductCategoryGuid == Guid.Empty)
                            //{
                            //    category.ProductCategoryGuid = category.ProductCategoryGuid;
                            //}
                            //else
                            //{
                            //    category.ProductCategoryGuid = ProductCategoryGuid;
                            //}
                            category.ProductCategoryGuid = ProductCategoryGuid;
                            category.MerchantGuid = item;
                            categoryQuery.Add(category);
                        }
                    }

                    //类型数据补充 Bing
                    var productTypeGuid = Guid.Empty;
                    var type = typeList.FirstOrDefault(c => c.OriginalProductTypeGuid == model.ProductTypeGuid && c.MerchantGuid == item.Value);
                    if (type != null)
                    {
                        productTypeGuid = type.ProductTypeGuid;

                    }

                    //商品
                    entity.ProductGuid = tempGuid;
                    entity.ProductCategoryGuid = ProductCategoryGuid;
                    entity.ProductTypeGuid = productTypeGuid;
                    entity.MerchantGuid = item;
                    entity.ProductName = model.ProductName;
                    entity.ProductUrl = "http://" + merchant.UserID + string.Format(".shop.{0}/wxshop/productinfo?productsguid={1}", CurrentManage.DomainWxRoot, entity.ProductGuid);
                    var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + RadomCode.DigitalCode(3) + ".png";
                    if (Common.QrCodeHelper.GenerationQrCode(entity.ProductUrl, "", basePath + fileName))
                    {
                        entity.QRCodeUrl = "/upload/qrcode/" + fileName;
                    }
                    entity.ProductCode = model.ProductCode;
                    entity.MarketPrice = model.MarketPrice;
                    entity.Price = model.Price;
                    entity.MinPrice = minPrice;
                    entity.MaxPrice = maxPrice;
                    entity.IsAgentsProduct = false;
                    entity.Inventory = model.Inventory;
                    entity.Weight = model.Weight;
                    entity.SalesVolume = model.SalesVolume;
                    entity.BaseSalesVolume = model.BaseSalesVolume;
                    entity.ProductImage = model.ProductImage;
                    entity.ProductImage1 = model.ProductImage1;
                    entity.ProductImage2 = model.ProductImage2;
                    entity.ProductImage3 = model.ProductImage3;
                    entity.ProductImage4 = model.ProductImage4;
                    entity.ProductImage5 = model.ProductImage5;
                    entity.FirstCommission = model.FirstCommission;
                    entity.SecondCommission = model.SecondCommission;
                    entity.ThirdCommission = model.ThirdCommission;
                    entity.IsDefault = model.IsDefault;
                    entity.Description = model.Description;
                    entity.InventoryWay = model.InventoryWay;
                    entity.Recommend = model.Recommend;
                    entity.Quota = model.Quota;
                    entity.IsPutaway = true;
                    entity.Sort = model.Sort;
                    entity.IsProperty = model.IsProperty;
                    entity.IsStandards = model.IsStandards;
                    entity.PutawayDate = DateTime.Now;
                    entity.OriginalProductGuid = model.ProductGuid;
                    entity.AgentsIsPutaway = model.AgentsIsPutaway;
                    entity.TemplatesGuid = model.TemplatesGuid;
                    entity.CommissionType = model.CommissionType;
                    entity.FirstCommissionAmount = model.FirstCommissionAmount;
                    entity.SecondCommissionAmount = model.SecondCommissionAmount;
                    entity.ThirdCommissionAmount = model.ThirdCommissionAmount;
                    entity.NoDelivery = model.NoDelivery;
                    entity.NoReceive = model.NoReceive;
                    entity.CategoryCode = model.CategoryCode;
                    entity.ProductClassify = model.ProductClassify;
                    entity.SMerchantGuid = item;

                    list.Add(entity);
                }
                trans.BeginTransaction();

                try
                {
                    query.AddList(list);

                    query.Update(m => new object[] { m.IsAgentsProduct == true, m.MinPrice == minPrice, m.MaxPrice == maxPrice, m.AgentsIsPutaway == true }, c => c.ProductGuid == productGuid && c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid);

                    if (model.IsStandards)
                    {
                        var list_TopSku = query_sku.GetList(c => c.ProductGuid == model.ProductGuid && c.MerchantGuid == CurrentManage.MerchantGuid, isFilterMerchant: false);

                        var list_SubSku = query_sku.GetList(c => c.OriginalProductSKUGuid.SqlIn(list_TopSku.Select(k => k.ProductSKUGuid.ToString()).ToArray()) && c.MerchantGuid.SqlIn(guids)).ToList();
                        if (list_TopSku.Count > 0 && list_SubSku.Count > 0)
                        {
                            foreach (var subSku in list_SubSku)
                            {
                                var tempProduct = list.FirstOrDefault(s => s.MerchantGuid == subSku.MerchantGuid);
                                if (tempProduct == null)
                                {
                                    continue;
                                }
                                subSku.ProductGuid = tempProduct.ProductGuid;
                                subSku.EntityState = EntityStates.ToBeUpdated;

                            }

                            query_sku.UpdateList(list_SubSku);

                        }
                        //if (list_TopSku != null && list_TopSku.Count > 0)
                        //{
                        //    query_sku.Update(s => new object[]{
                        //        s.ProductGuid==tempGuid
                        //        }, s => s.MerchantGuid.SqlIn(guids) && s.OriginalProductSKUGuid.SqlIn(list_TopSku.Select(c => c.ProductSKUGuid.ToString()).ToArray()), isFilterMerchant: false);
                        //}
                    }

                    //if (model.IsStandards == true)
                    //{
                    //    result = ProductSKUManage.CopySKUData(CurrentManage.MerchantGuid, list, trans);
                    //}
                    //if (!result.State)
                    //{
                    //    trans.Rollback();
                    //    return new Result(false, result.Msg);
                    //}
                    //else
                    //{
                    //    trans.Commit();
                    //    return new Result(true);
                    //}
                    trans.Commit();
                    return new Result(true);
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return new Result(false, ex.Message);
                }
            }
        }


        #region 导入/同步 商品相关数据 Bing 暂定
        /// <summary>
        /// 导入/同步 商品相关数据 Bing 暂定
        /// </summary>
        /// <param name="action"></param>
        /// <param name="guids"></param>
        /// <returns></returns>
        public static Result ImportProductInfoTemp(string action, Guid?[] guids)
        {
            if (guids == null || guids.Length == 0)
            {
                return new Result(true);
                // return new Result(false, "找不到下级代理！");
            }

            using (SqlRTransaction tran = new SqlRTransaction())
            {
                try
                {
                    tran.BeginTransaction();

                    var query_products = Factory.CreateT_BAS_Products(tran);
                    var query_productCategory = Factory.CreateT_BAS_ProductCategorys(tran);
                    var query_productType = Factory.CreateT_BAS_ProductType(tran);
                    var query_skuName = Factory.CreateT_BAS_ProductSKUName(tran);
                    var query_skuValue = Factory.CreateT_BAS_ProductSKUValue(tran);
                    var query_sku = Factory.CreateT_BAS_ProductSKU(tran);
                    var query_merchant = Factory.CreateT_BAS_Merchants(tran);

                    List<T_BAS_ProductType> oldProductTypeList = new List<T_BAS_ProductType>();
                    List<T_BAS_ProductType> addProductTypeList = new List<T_BAS_ProductType>();
                    List<T_BAS_ProductSKUName> oldProductSKUNameList = new List<T_BAS_ProductSKUName>();
                    List<T_BAS_ProductSKUName> addProductSKUNameList = new List<T_BAS_ProductSKUName>();
                    List<T_BAS_ProductSKUValue> oldProductSKUValueList = new List<T_BAS_ProductSKUValue>();
                    List<T_BAS_ProductSKUValue> addProductSKUValueList = new List<T_BAS_ProductSKUValue>();

                    var merchantList = query_merchant.GetList(m => m.MerchantGuid.SqlIn(guids.Select(c => c.Value).ToArray()), isFilterMerchant: false);
                    var newGuids = new List<Guid?>();
                    var currGuids = merchantList.Select(c => c.MerchantGuid).ToList();
                    currGuids.ForEach(c =>
                    {
                        newGuids.Add(c);
                    });
                    guids = newGuids.ToArray();


                    ImportCategoryTemp(guids, query_productCategory);

                    ImportTypeTemp(guids, query_productType, ref addProductTypeList, ref oldProductTypeList);

                    ImportSKUNameTemp(guids, addProductTypeList, oldProductTypeList, query_skuName, ref addProductSKUNameList, ref oldProductSKUNameList);

                    ImportSKUValueTemp(guids, addProductSKUNameList, oldProductSKUNameList, query_skuValue, ref addProductSKUValueList, ref oldProductSKUValueList);

                    ImportSKUTemp(guids, addProductTypeList, addProductSKUNameList, addProductSKUValueList, oldProductTypeList, oldProductSKUNameList, oldProductSKUValueList, query_sku, query_products);

                    tran.Commit();
                    return new Result(true, "操作成功");

                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    Wechat.LogManage.Log("导入/同步 商品相关数据 ImportProductInfoTemp：" + ex.ToString());
                    return new Result(false, "操作失败：" + ex.Message);
                }

            }

        }
        #endregion

        #region 同步商品分类 关联方法 Bing 暂定
        /// <summary>
        /// 同步商品分类 关联方法 Bing 暂定
        /// </summary>
        /// <param name="guids"></param>
        /// <param name="tran"></param>
        /// <returns></returns>
        private static void ImportCategoryTemp(Guid?[] guids, IQuery<T_BAS_ProductCategorys> queryProductCategory)
        {
            var topCategoryList = queryProductCategory.GetList(a => a.MerchantGuid == CurrentManage.MerchantGuid, false, null, OrderMethods.Default, LockType.NOLOCK, false);

            var subCategoryList = queryProductCategory.GetList(c => c.MerchantGuid.SqlIn(guids), false, null, OrderMethods.Default, LockType.NOLOCK, false);
            subCategoryList = (subCategoryList ?? new List<T_BAS_ProductCategorys>());

            if (topCategoryList != null && topCategoryList.Count > 0)
            {
                topCategoryList = topCategoryList.OrderBy(a => a.Levels).ThenBy(a => a.Sort).ToList();

                foreach (var sub in guids)
                {
                    foreach (var item in topCategoryList)
                    {
                        var category = new T_BAS_ProductCategorys()
                        {
                            MerchantGuid = sub,
                            CategoryName = item.CategoryName,
                            CategoryCode = item.CategoryCode,
                            Url = item.Url,
                            Levels = item.Levels,
                            Sort = item.Sort,
                            SMerchantGuid = sub
                        };

                        bool isExist = subCategoryList.Exists(a => a.MerchantGuid == sub && a.CategoryName == item.CategoryName);

                        if (isExist)
                        {
                            var _model = subCategoryList.FirstOrDefault(a => a.MerchantGuid == sub && a.CategoryName == item.CategoryName);
                            if (_model != null)
                            {
                                category.ProductCategoryGuid = _model.ProductCategoryGuid;
                            }

                            if (item.ParentGuid != null)
                            {
                                var model = subCategoryList.FirstOrDefault(a => a.OriginalProductCategoryGuid == item.ParentGuid && a.MerchantGuid == sub);
                                if (model != null)
                                {
                                    category.ParentGuid = model.ProductCategoryGuid;
                                }
                                else
                                {
                                    string categoryName = topCategoryList.Where(a => a.ProductCategoryGuid == item.ParentGuid).Select(a => a.CategoryName).FirstOrDefault();

                                    model = subCategoryList.FirstOrDefault(a => a.CategoryName == categoryName && a.MerchantGuid == sub);
                                    if (model != null)
                                    {
                                        category.ParentGuid = model.ProductCategoryGuid;
                                    }
                                }
                            }

                            queryProductCategory.Update(category, false);
                            subCategoryList = queryProductCategory.GetList(c => c.MerchantGuid.SqlIn(guids), false, null, OrderMethods.Default, LockType.NOLOCK, false);
                            subCategoryList = (subCategoryList ?? new List<T_BAS_ProductCategorys>());
                        }
                        else
                        {
                            category.OriginalProductCategoryGuid = item.ProductCategoryGuid;
                            category.ProductCategoryGuid = Guid.NewGuid();

                            if (item.ParentGuid != null)
                            {
                                var model = subCategoryList.FirstOrDefault(a => a.OriginalProductCategoryGuid == item.ParentGuid && a.MerchantGuid == sub);
                                if (model != null)
                                {
                                    category.ParentGuid = model.ProductCategoryGuid;
                                }
                                else
                                {
                                    string categoryName = topCategoryList.Where(a => a.ProductCategoryGuid == item.ParentGuid).Select(a => a.CategoryName).FirstOrDefault();
                                    model = subCategoryList.FirstOrDefault(a => a.CategoryName == categoryName && a.MerchantGuid == sub);
                                    if (model != null)
                                    {
                                        category.ParentGuid = model.ProductCategoryGuid;

                                    };
                                }
                            }

                            queryProductCategory.Add(category);
                            subCategoryList.Add(category);
                        }
                    }
                }
            }
        }
        #endregion

        #region 同步商品类型 关联方法 Bing 暂定
        /// <summary>
        /// 同步商品类型 关联方法 Bing 暂定
        /// </summary>
        /// <returns></returns>
        private static void ImportTypeTemp(Guid?[] guids, IQuery<T_BAS_ProductType> query_productType, ref List<T_BAS_ProductType> addProductTypeList, ref List<T_BAS_ProductType> oldProductTypeList)
        {
            var topTypeList = query_productType.GetList(m => m.MerchantGuid == CurrentManage.MerchantGuid, flag: LockType.NOLOCK);

            if (topTypeList != null && topTypeList.Count > 0)
            {
                query_productType.Delete(c => c.MerchantGuid.SqlIn(guids), isFilterMerchant: false);

                foreach (var sub in guids)
                {
                    List<T_BAS_ProductType> addList = new List<T_BAS_ProductType>();

                    foreach (var item in topTypeList)
                    {
                        var type = new T_BAS_ProductType()
                        {
                            OriginalProductTypeGuid = item.ProductTypeGuid,
                            ProductTypeGuid = Guid.NewGuid(),
                            MerchantGuid = sub,
                            SMerchantGuid = sub,
                            Sort = item.Sort,
                            ProductTypeName = item.ProductTypeName,
                            Remark = item.Remark,
                            EntityState = EntityStates.ToBeAdd
                        };
                        addList.Add(type);
                    }
                    if (addList.Count > 0)
                    {
                        addProductTypeList.AddRange(addList);
                    }
                }

                if (addProductTypeList.Count > 0)
                {
                    query_productType.AddList(addProductTypeList);
                }
            }
            else
            {
                oldProductTypeList = (query_productType.GetList(m => m.MerchantGuid.SqlIn(guids), flag: LockType.NOLOCK, isFilterMerchant: false) ?? new List<T_BAS_ProductType>());

            }
        }
        #endregion

        #region 同步规格名称 关联方法 Bing 暂定
        /// <summary>
        /// 同步规格名称 关联方法 Bing 暂定
        /// </summary>
        /// <param name="guids"></param>
        /// <param name="addProductTypeList"></param>
        /// <param name="addProductSKUNameList"></param>
        /// <param name="query_productType"></param>
        /// <returns></returns>
        public static void ImportSKUNameTemp(Guid?[] guids, List<T_BAS_ProductType> addProductTypeList, List<T_BAS_ProductType> oldProductTypeList, IQuery<T_BAS_ProductSKUName> query_skuName, ref List<T_BAS_ProductSKUName> addProductSKUNameList, ref List<T_BAS_ProductSKUName> oldProductSKUNameList)
        {
            var topSKUNameList = query_skuName.GetList(m => m.MerchantGuid == CurrentManage.MerchantGuid, flag: LockType.NOLOCK);

            if (topSKUNameList != null && topSKUNameList.Count > 0)
            {
                query_skuName.Delete(c => c.MerchantGuid.SqlIn(guids), isFilterMerchant: false);

                foreach (var sub in guids)
                {
                    List<T_BAS_ProductSKUName> addList = new List<T_BAS_ProductSKUName>();

                    foreach (var item in topSKUNameList)
                    {
                        var skuName = new T_BAS_ProductSKUName()
                        {
                            OriginalProductSKUNameGuid = item.ProductSKUNameGuid,
                            ProductSKUNameGuid = Guid.NewGuid(),
                            MerchantGuid = sub,
                            SMerchantGuid = sub,
                            Sort = item.Sort,
                            Name = item.Name,
                            EntityState = EntityStates.ToBeAdd
                        };

                        var type = addProductTypeList.FirstOrDefault(c => c.OriginalProductTypeGuid == item.ProductTypeGuid && c.MerchantGuid == sub.Value);
                        type = (type ?? oldProductTypeList.FirstOrDefault(c => c.OriginalProductTypeGuid == item.ProductTypeGuid && c.MerchantGuid == sub.Value));

                        if (type != null)
                        {
                            skuName.ProductTypeGuid = type.ProductTypeGuid;
                        }


                        addList.Add(skuName);
                    }
                    if (addList.Count > 0)
                    {
                        addProductSKUNameList.AddRange(addList);
                    }
                }
                if (addProductSKUNameList.Count > 0)
                {

                    query_skuName.AddList(addProductSKUNameList);

                }
            }
            else
            {
                oldProductSKUNameList = (query_skuName.GetList(m => m.MerchantGuid.SqlIn(guids), flag: LockType.NOLOCK, isFilterMerchant: false) ?? new List<T_BAS_ProductSKUName>());
            }


        }

        #endregion

        #region 同步规格值 关联方法 Bing 暂定
        /// <summary>
        /// 同步规格值 关联方法 Bing 暂定
        /// </summary>
        /// <param name="guids"></param>
        /// <param name="addProductTypeList"></param>
        /// <param name="addProductSKUNameList"></param>
        /// <param name="tran"></param>
        /// <returns></returns>
        public static void ImportSKUValueTemp(Guid?[] guids, List<T_BAS_ProductSKUName> addProductSKUNameList, List<T_BAS_ProductSKUName> oldProductSKUNameList, IQuery<T_BAS_ProductSKUValue> query_skuValue, ref List<T_BAS_ProductSKUValue> addProductSKUValueList, ref List<T_BAS_ProductSKUValue> oldProductSKUValueList)
        {
            var topSKUValue = query_skuValue.GetList(m => m.MerchantGuid == CurrentManage.MerchantGuid, flag: LockType.NOLOCK);
            if (topSKUValue != null && topSKUValue.Count > 0)
            {
                query_skuValue.Delete(c => c.MerchantGuid.SqlIn(guids), isFilterMerchant: false);

                foreach (var sub in guids)
                {
                    List<T_BAS_ProductSKUValue> addList = new List<T_BAS_ProductSKUValue>();

                    foreach (var item in topSKUValue)
                    {
                        var skuValue = new T_BAS_ProductSKUValue()
                        {
                            ProductSKUValueGuid = Guid.NewGuid(),
                            OriginalProductSKUValueGuid = item.ProductSKUValueGuid,
                            ProductSKUValue = item.ProductSKUValue,
                            Sort = item.Sort,
                            MerchantGuid = sub,
                            SMerchantGuid = sub,
                            EntityState = EntityStates.ToBeAdd
                        };

                        var name = addProductSKUNameList.FirstOrDefault(c => c.OriginalProductSKUNameGuid == item.ProductSKUNameGuid && c.MerchantGuid == sub.Value);
                        name = (name ?? oldProductSKUNameList.FirstOrDefault(c => c.OriginalProductSKUNameGuid == item.ProductSKUNameGuid && c.MerchantGuid == sub.Value));
                        if (name != null)
                        {
                            skuValue.ProductSKUNameGuid = name.ProductSKUNameGuid;
                        }

                        addList.Add(skuValue);

                    }
                    if (addList.Count > 0)
                    {
                        addProductSKUValueList.AddRange(addList);
                    }
                }
                if (addProductSKUValueList.Count > 0)
                {
                    query_skuValue.AddList(addProductSKUValueList);
                }
            }
            else
            {
                oldProductSKUValueList = (query_skuValue.GetList(m => m.MerchantGuid.SqlIn(guids), flag: LockType.NOLOCK, isFilterMerchant: false) ?? new List<T_BAS_ProductSKUValue>());
            }


        }

        #endregion

        #region 同步商品规格 关联方法 Bing 暂定
        /// <summary>
        /// 同步商品规格 关联方法 Bing 暂定
        /// </summary>
        /// <param name="guids"></param>
        /// <param name="addProductTypeList"></param>
        /// <param name="addProductSKUNameList"></param>
        /// <param name="addProductSKUValueList"></param>
        /// <param name="query_productType"></param>
        /// <param name="query_skuName"></param>
        /// <param name="query_skuValue"></param>
        /// <param name="query_sku"></param>
        /// <param name="query_products"></param>
        /// <returns></returns>
        private static void ImportSKUTemp(Guid?[] guids,
            List<T_BAS_ProductType> addProductTypeList,
            List<T_BAS_ProductSKUName> addProductSKUNameList,
            List<T_BAS_ProductSKUValue> addProductSKUValueList,
            List<T_BAS_ProductType> oldProductTypeList,
            List<T_BAS_ProductSKUName> oldProductSKUNameList,
            List<T_BAS_ProductSKUValue> oldProductSKUValueList, IQuery<T_BAS_ProductSKU> query_sku, IQuery<T_BAS_Products> query_products)
        {
            var topProductList = query_products.GetList(a => a.MerchantGuid == Common.CurrentManage.MerchantGuid && a.IsStandards == true, flag: LockType.NOLOCK);
            var topSKUList = new List<T_BAS_ProductSKU>();
            if (topProductList != null && topProductList.Count > 0)
            {
                topSKUList = query_sku.GetList(a => a.MerchantGuid == CurrentManage.MerchantGuid && a.ProductGuid.SqlIn(topProductList.Select(c
=> c.ProductGuid).ToArray()), flag: LockType.NOLOCK, isFilterMerchant: false);
            }

            if (topSKUList != null && topSKUList.Count > 0)
            {

                query_sku.Delete(c => c.MerchantGuid.SqlIn(guids), isFilterMerchant: false);

                List<T_BAS_ProductSKU> addList = new List<T_BAS_ProductSKU>();
                foreach (var sub in guids)
                {
                    foreach (var topProduct in topProductList)
                    {
                        List<T_BAS_ProductSKU> list_sku = new List<T_BAS_ProductSKU>();
                        var tempSkuList = topSKUList.Where(c => c.ProductGuid == topProduct.ProductGuid);
                        foreach (var topSKU in tempSkuList)
                        {
                            var skuname = addProductSKUNameList.FirstOrDefault(c => c.OriginalProductSKUNameGuid == topSKU.ProductSKUNameGuid && c.MerchantGuid == sub.Value);
                            skuname = (skuname ?? oldProductSKUNameList.FirstOrDefault(c => c.OriginalProductSKUNameGuid == topSKU.ProductSKUNameGuid && c.MerchantGuid == sub.Value));

                            var skuvalue = addProductSKUValueList.FirstOrDefault(c => c.OriginalProductSKUValueGuid == topSKU.ProductSKUValueGuid && c.MerchantGuid == sub.Value);
                            skuvalue = (skuvalue ?? oldProductSKUValueList.FirstOrDefault(c => c.OriginalProductSKUValueGuid == topSKU.ProductSKUValueGuid && c.MerchantGuid == sub.Value));

                            if (skuname == null || skuvalue == null)
                            {
                                continue;
                            }
                            T_BAS_ProductSKU sku = new T_BAS_ProductSKU()
                            {
                                ProductSKUGuid = Guid.NewGuid(),
                                ProductSKUNameGuid = (skuname.ProductSKUNameGuid),
                                ProductSKUValueGuid = (skuvalue.ProductSKUValueGuid),
                                ProductSKUGroupGuid = topSKU.ProductSKUGroupGuid,
                                Price = topSKU.Price,
                                Invenotory = topSKU.Invenotory,
                                Code = topSKU.Code,
                                Weight = topSKU.Weight,
                                Sort = topSKU.Sort,
                                OriginalProductSKUGuid = topSKU.ProductSKUGuid,
                                MerchantGuid = sub,
                                SMerchantGuid = sub,
                                EntityState = EntityStates.ToBeAdd
                            };
                            list_sku.Add(sku);
                        }

                        if (list_sku.Count > 0)
                        {
                            addList.AddRange(list_sku);
                        }

                        #region 已移植备份
                        //var type = addProductTypeList.FirstOrDefault(c => c.OriginalProductTypeGuid == topProduct.ProductTypeGuid && c.MerchantGuid == sub.Value);
                        //type = (type ?? oldProductTypeList.FirstOrDefault(c => c.OriginalProductTypeGuid == topProduct.ProductTypeGuid && c.MerchantGuid == sub.Value));

                        //if (type != null)
                        //{
                        //    query_products.Update(a => new Object[] {
                        //        a.ProductTypeGuid == type.ProductTypeGuid 
                        //    }, a => a.OriginalProductGuid == topProduct.ProductGuid && a.MerchantGuid == sub.Value, false);
                        //} 
                        #endregion
                    }
                }
                if (addList.Count > 0)
                {
                    query_sku.AddList(addList);
                }
            }
        }

        #endregion


        private static bool isExistType(Guid?[] guids, IQuery<T_BAS_ProductType> typeQuery)
        {
            var flag = true;
            var typeList = typeQuery.GetList(a => a.MerchantGuid == Common.CurrentManage.MerchantGuid);
            if (typeList.Count == 0) return false;
            foreach (var guid in guids)
            {
                foreach (var item in typeList)
                {
                    flag = typeQuery.IsExist(a => a.OriginalProductTypeGuid == item.ProductTypeGuid && a.MerchantGuid == guid, false);
                    if (flag == false) break;
                }
            }
            return flag;
        }

        private static bool IsExistCateGory(Guid?[] guids, string categoryName, IQuery<T_BAS_ProductCategorys> categoryQuery)
        {
            var count = categoryQuery.GetCount(a => a.MerchantGuid.SqlIn(guids) && a.CategoryName == categoryName, isFilterMerchant: false);
            if (count == guids.Length)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 导入商品分类、商品类型、规格名称、规格值
        /// </summary>
        /// <returns></returns>
        public static Result ImportProductInfo(string action)
        {
            var guids = AgentsFlagshipManage.GetSubMerchantList().Select(m => m.MerchantGuid).ToArray();
            if (guids == null || guids.Length == 0) return new Result(false, "找不到下级代理！");
            switch (action)
            {
                case "1":
                    return ImportCategory(guids);
                case "2":
                    return ImportSKUInfo(guids);
                default:
                    Result result = ImportCategory(guids);
                    if (result.State)
                    {
                        return ImportSKUInfo(guids);
                    }
                    else
                    {
                        return result;
                    }
            }

        }

        /// <summary>
        /// 同步商品分类
        /// </summary>
        /// <returns></returns>
        private static Result ImportCategory(Guid?[] guids)
        {
            try
            {
                using (var queryProductCategory = Factory.CreateT_BAS_ProductCategorys())
                {
                    var topCategory = queryProductCategory.GetList(a => a.MerchantGuid == CurrentManage.MerchantGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                    if (topCategory.Count > 0)
                    {
                        topCategory = topCategory.OrderBy(a => a.Levels).ThenBy(a => a.Sort).ToList();
                        foreach (var sub in guids)
                        {
                            foreach (var item in topCategory)
                            {
                                var category = new T_BAS_ProductCategorys()
                                {
                                    MerchantGuid = sub,
                                    CategoryName = item.CategoryName,
                                    CategoryCode = item.CategoryCode,
                                    Url = item.Url,
                                    Levels = item.Levels,
                                    Sort = item.Sort,
                                    SMerchantGuid = sub
                                };
                                var isExist = queryProductCategory.IsExist(a => a.MerchantGuid == sub && a.CategoryName == item.CategoryName, isFilterMerchant: false);
                                if (isExist)
                                {
                                    var _model = queryProductCategory.GetFirstData(a => a.MerchantGuid == sub && a.CategoryName == item.CategoryName, isFilterMerchant: false);
                                    if (_model != null)
                                    {
                                        category.ProductCategoryGuid = _model.ProductCategoryGuid;
                                    }
                                    if (item.ParentGuid != null)
                                    {
                                        var model = queryProductCategory.GetFirstData(a => a.OriginalProductCategoryGuid == item.ParentGuid && a.MerchantGuid == sub, isFilterMerchant: false);
                                        if (model != null)
                                        {
                                            category.ParentGuid = model.ProductCategoryGuid;
                                        }
                                        else
                                        {
                                            string categoryName = topCategory.Where(a => a.ProductCategoryGuid == item.ParentGuid).Select(a => a.CategoryName).FirstOrDefault();
                                            model = queryProductCategory.GetFirstData(a => a.CategoryName == categoryName && a.MerchantGuid == sub, isFilterMerchant: false);
                                            if (model != null)
                                            {
                                                category.ParentGuid = model.ProductCategoryGuid;
                                            }
                                        }
                                    }
                                    queryProductCategory.Update(category, false);
                                }
                                else
                                {
                                    category.OriginalProductCategoryGuid = item.ProductCategoryGuid;
                                    category.ProductCategoryGuid = Guid.NewGuid();
                                    if (item.ParentGuid != null)
                                    {
                                        var model = queryProductCategory.GetFirstData(a => a.OriginalProductCategoryGuid == item.ParentGuid && a.MerchantGuid == sub, isFilterMerchant: false);
                                        if (model != null)
                                        {
                                            category.ParentGuid = model.ProductCategoryGuid;
                                        }
                                        else
                                        {
                                            string categoryName = topCategory.Where(a => a.ProductCategoryGuid == item.ParentGuid).Select(a => a.CategoryName).FirstOrDefault();
                                            model = queryProductCategory.GetFirstData(a => a.CategoryName == categoryName && a.MerchantGuid == sub, isFilterMerchant: false);
                                            if (model != null) category.ParentGuid = model.ProductCategoryGuid;
                                        }
                                    }
                                    queryProductCategory.Add(category);
                                }
                            }
                        }
                    }
                }
                return new Result(true);
            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }

        /// <summary>
        /// 同步规格信息
        /// </summary>
        /// <param name="guids"></param>
        /// <returns></returns>
        private static Result ImportSKUInfo(Guid?[] guids)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    Result result;
                    var query_productType = Factory.CreateT_BAS_ProductType(tran);
                    var query_skuName = Factory.CreateT_BAS_ProductSKUName(tran);
                    var query_skuValue = Factory.CreateT_BAS_ProductSKUValue(tran);
                    List<T_BAS_ProductType> addProductTypeList = new List<T_BAS_ProductType>();
                    List<T_BAS_ProductSKUName> addProductSKUNameList = new List<T_BAS_ProductSKUName>();
                    //同步商品类型
                    result = ImportType(guids, query_productType, ref addProductTypeList);
                    if (!result.State) return result;
                    //同步规格名称
                    result = ImportSKUName(guids, addProductTypeList, query_productType, query_skuName, ref addProductSKUNameList);
                    if (!result.State) return result;
                    //同步规格值
                    result = ImportSKUValue(guids, addProductSKUNameList, query_skuName, query_skuValue);
                    if (!result.State) return result;
                    return new Result(true);
                }
            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }

        /// <summary>
        /// 同步规格信息
        /// </summary>
        /// <param name="guids"></param>
        /// <returns></returns>
        public static Result ImportSKUInfo(Guid?[] guids, SqlRTransaction tran)
        {
            try
            {
                Result result;
                var query_productType = Factory.CreateT_BAS_ProductType(tran);
                var query_skuName = Factory.CreateT_BAS_ProductSKUName(tran);
                var query_skuValue = Factory.CreateT_BAS_ProductSKUValue(tran);
                List<T_BAS_ProductType> addProductTypeList = new List<T_BAS_ProductType>();
                List<T_BAS_ProductSKUName> addProductSKUNameList = new List<T_BAS_ProductSKUName>();
                //同步商品类型
                result = ImportType(guids, query_productType, ref addProductTypeList);
                if (!result.State) return result;
                //同步规格名称
                result = ImportSKUName(guids, addProductTypeList, query_productType, query_skuName, ref addProductSKUNameList);
                if (!result.State) return result;
                //同步规格值
                result = ImportSKUValue(guids, addProductSKUNameList, query_skuName, query_skuValue);
                if (!result.State) return result;
                return new Result(true);

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

        /// <summary>
        /// 同步商品类型
        /// </summary>
        /// <returns></returns>
        private static Result ImportType(Guid?[] guids, IQuery<T_BAS_ProductType> query_productType, ref List<T_BAS_ProductType> addProductTypeList)
        {
            try
            {
                //复制商品类型
                var lstType = query_productType.GetList(m => m.MerchantGuid == CurrentManage.MerchantGuid);
                if (lstType == null || lstType.Count == 0) return new Result(false, "找不到商品类型数据！");

                foreach (var item in lstType)
                {
                    query_productType.Update(m => new object[] { m.ProductTypeName == item.ProductTypeName, m.Remark == item.Remark, m.Sort == item.Sort }, v => v.MerchantGuid.SqlIn(guids) && v.OriginalProductTypeGuid == item.ProductTypeGuid, false);

                    var src_list = query_productType.GetList(m => m.MerchantGuid.SqlIn(guids) && m.OriginalProductTypeGuid == item.ProductTypeGuid);

                    var notExists = guids.Where(m => !src_list.Exists(v => v.MerchantGuid == m));

                    if (notExists != null && notExists.Count() > 0)
                    {
                        List<T_BAS_ProductType> addList = new List<T_BAS_ProductType>();

                        foreach (var sub in notExists)
                        {
                            addList.Add(new T_BAS_ProductType()
                            {
                                OriginalProductTypeGuid = item.ProductTypeGuid,
                                ProductTypeGuid = Guid.NewGuid(),
                                MerchantGuid = sub,
                                SMerchantGuid = sub,
                                Sort = item.Sort,
                                ProductTypeName = item.ProductTypeName,
                                Remark = item.Remark,
                                EntityState = EntityStates.ToBeAdd
                            });
                        }
                        if (addList.Count > 0)
                        {
                            query_productType.AddList(addList);
                            addProductTypeList.AddRange(addList);
                        }
                    }
                }
                return new Result(true);
            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }
        /// <summary>
        /// 复制规格名称
        /// </summary>
        /// <param name="guids"></param>
        /// <param name="addProductTypeList"></param>
        /// <param name="addProductSKUNameList"></param>
        /// <param name="query_productType"></param>
        /// <returns></returns>
        public static Result ImportSKUName(Guid?[] guids, List<T_BAS_ProductType> addProductTypeList, IQuery<T_BAS_ProductType> query_productType, IQuery<T_BAS_ProductSKUName> query_skuName, ref List<T_BAS_ProductSKUName> addProductSKUNameList)
        {
            try
            {
                var lstSKUName = query_skuName.GetList(m => m.MerchantGuid == CurrentManage.MerchantGuid);
                if (lstSKUName == null || lstSKUName.Count == 0) return new Result(false, "找不到规格名称数据！");

                foreach (var item in lstSKUName)
                {
                    //判断商品规格名称是否存在，存在则更新，否则新增
                    query_skuName.Update(a => new Object[] { a.Name == item.Name, a.Sort == item.Sort }, a => a.OriginalProductSKUNameGuid == item.ProductSKUNameGuid && a.MerchantGuid.SqlIn(guids), false);

                    var src_list = query_skuName.GetList(m => m.MerchantGuid.SqlIn(guids) && m.OriginalProductSKUNameGuid == item.ProductSKUNameGuid);

                    var notExists = guids.Where(m => !src_list.Exists(v => v.MerchantGuid == m));

                    if (notExists != null && notExists.Count() > 0)
                    {

                        List<T_BAS_ProductSKUName> addList = new List<T_BAS_ProductSKUName>();
                        foreach (var sub in notExists)
                        {
                            var type = ProductSKUManage.GetProductType(item.ProductTypeGuid, sub.Value, addProductTypeList, query_productType);

                            var skuName = new T_BAS_ProductSKUName()
                            {
                                OriginalProductSKUNameGuid = item.ProductSKUNameGuid,
                                ProductSKUNameGuid = Guid.NewGuid(),
                                MerchantGuid = sub,
                                SMerchantGuid = sub,
                                Sort = item.Sort,
                                Name = item.Name,
                                EntityState = EntityStates.ToBeAdd
                            };
                            if (type != null) skuName.ProductTypeGuid = type.ProductTypeGuid;

                            addList.Add(skuName);
                        }
                        if (addList.Count > 0)
                        {
                            query_skuName.AddList(addList);
                            addProductSKUNameList.AddRange(addList);
                        }
                    }
                }
                return new Result(true);
            }
            catch (Exception err)
            {
                return new Result(false, err.Message);
            }
        }
        /// <summary>
        /// 复制规格值
        /// </summary>
        /// <param name="guids">下级代理Guid[]</param>
        /// <param name="addProductTypeList"></param>
        /// <param name="addProductSKUNameList"></param>
        /// <param name="tran"></param>
        /// <returns></returns>
        public static Result ImportSKUValue(Guid?[] guids, List<T_BAS_ProductSKUName> addProductSKUNameList, IQuery<T_BAS_ProductSKUName> query_skuName, IQuery<T_BAS_ProductSKUValue> query_skuValue)
        {
            try
            {
                List<T_BAS_ProductSKUValue> addProductSKUValueList = new List<T_BAS_ProductSKUValue>();
                var lstSKUValue = query_skuValue.GetList(m => m.MerchantGuid == CurrentManage.MerchantGuid);
                if (lstSKUValue == null || lstSKUValue.Count == 0) return new Result(false, "找不到规格值数据！");
                foreach (var item in lstSKUValue)
                {
                    //判断商品规格名称是否存在，存在则更新，否则新增
                    query_skuValue.Update(a => new Object[] { a.ProductSKUValue == item.ProductSKUValue, a.Sort == item.Sort }, a => a.OriginalProductSKUValueGuid == item.ProductSKUValueGuid && a.MerchantGuid.SqlIn(guids), false);

                    var src_list = query_skuValue.GetList(m => m.MerchantGuid.SqlIn(guids) && m.OriginalProductSKUValueGuid == item.OriginalProductSKUValueGuid);

                    var notExists = guids.Where(m => !src_list.Exists(v => v.MerchantGuid == m));

                    if (notExists != null && notExists.Count() > 0)
                    {
                        List<T_BAS_ProductSKUValue> addList = new List<T_BAS_ProductSKUValue>();

                        foreach (var sub in notExists)
                        {
                            var name = ProductSKUManage.GetProductSKUName(item.ProductSKUNameGuid, sub.Value, addProductSKUNameList, query_skuName);

                            var skuValue = new T_BAS_ProductSKUValue()
                            {
                                OriginalProductSKUValueGuid = item.ProductSKUValueGuid,
                                ProductSKUValueGuid = Guid.NewGuid(),
                                MerchantGuid = sub,
                                ProductSKUValue = item.ProductSKUValue,
                                Sort = item.Sort,
                                SMerchantGuid = sub,
                                EntityState = EntityStates.ToBeAdd
                            };
                            if (name != null) skuValue.ProductSKUNameGuid = name.ProductSKUNameGuid;

                            addList.Add(skuValue);
                        }
                        if (addList.Count > 0)
                        {
                            query_skuValue.AddList(addList);
                            addProductSKUValueList.AddRange(addList);
                        }

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


        public static T_BAS_Products GetProductByGuid(Guid productGuid)
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                return query.GetFirstData(c => c.IsPutaway == true && c.ProductGuid == productGuid && c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid, false, b => b.Sort, isFilterMerchant: false);
            }
        }

        public static T_BAS_Products GetProductByGuidPutaway(Guid productGuid)
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                return query.GetFirstData(c => c.ProductGuid == productGuid && c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid, false, b => b.Sort, OrderMethods.Default, LockType.Default, false);
            }
        }

        public static T_BAS_Products GetProductByOriginalProductGuid(Guid OriginalProductGuid)
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                return query.GetDataByGuid(OriginalProductGuid, false);
            }
        }


        public static List<PT_BAS_ProductByPage> GetProductByPages(int pageIndex, string categoty, string searchKey, string orderKey, int pageSize = 4)
        {
            using (var query = Factory.CreateProcedure())
            {
                var a = query.GetProductByPages(pageIndex, pageSize, searchKey, orderKey, categoty);
                return a;
            }
        }

        public static List<T_BAS_Products> GetProductByPages(out int pageCount, out int recordCount, string searchKey, Expression<Func<T_BAS_Products, object>> order, int pageIndex, int pageSize = 4)
        {
            searchKey = searchKey ?? String.Empty;
            using (var query = Factory.CreateT_BAS_Products())
            {
                return query.GetPageList(pageIndex, pageSize, out pageCount, out recordCount,
                c => c.IsPutaway == true && c.MerchantGuid == RFrameGenerate.Common.CurrentManage.MerchantGuid && c.ProductCode.SqlLike(searchKey), false
                , order);
            }
        }

        /// <summary>
        /// 获取商品数量
        /// </summary>
        /// <param name="sMerchantGuid"></param>
        /// <returns></returns>
        public static int GetCount(Guid sMerchantGuid)
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                return query.GetCount(a => a.MerchantGuid == sMerchantGuid && a.IsPutaway == true, false, false);
            }
        }
        /// <summary>
        /// 微信端生成商品二维码
        /// </summary>
        /// <param name="productsGuid"></param>
        /// <param name="did"></param>
        /// <returns></returns>
        public static T_BAS_Products GetShareProducts(Guid productsGuid, Guid did, string openID)
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                var entity = query.GetFirstData(a => a.IsPutaway == true && a.ProductGuid == productsGuid, isFilterMerchant: false);
                if (entity == null) return null;
                if (did != Guid.Empty)
                {
                    entity.ProductUrl = CurrentManage.CurrentDomainWx + "WxShop/productinfo?did=" + did + "&productsguid=" + entity.ProductGuid + "&inviter=" + openID;
                    //string basePath = AppDomain.CurrentDomain.BaseDirectory + @"upload\tempqrcode\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";    
                    string basePath = AppDomain.CurrentDomain.BaseDirectory + @"upload\tempqrcode\products\" + CurrentManage.MerchantUserID + "\\";
                    if (System.IO.Directory.Exists(basePath) != true)
                        System.IO.Directory.CreateDirectory(basePath);
                    var fileName = productsGuid.ToString() + CurrentUser.GetCurrUserGuid().ToString() + ".png";
                    if (System.IO.File.Exists(basePath + fileName) || QrCodeHelper.GenerationQrCode(entity.ProductUrl, "", basePath + fileName))
                    {
                        entity.QRCodeUrl = "/upload/tempqrcode/products/" + CurrentManage.MerchantUserID + "/" + fileName;//zhou 2016/3/11 防止产生多余的文件
                    }
                    return entity;
                }
                else
                {
                    return entity;
                }
            }
        }

        #region 根据订单名称获取产品
        /// <summary>
        ///根据订单名称获取产品
        /// </summary>
        /// <param name="orderGuid"></param>
        /// <returns></returns>
        public static string GetProducts(Guid orderGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                string products = "";
                var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                var list = query_orderDetail.GetList(a => a.OrderGuid == orderGuid);
                if (list == null || list.Count == 0) return "";
                foreach (var item in list)
                {
                    products += item.ProductName + ",";
                }
                return products.Substring(0, products.Length - 1);
            }
        }
        /// <summary>
        ///根据订单名称获取产品
        /// </summary>
        /// <param name="orderGuid"></param>
        /// <returns></returns>
        public static string GetProductsNotFilter(Guid orderGuid)
        {
            using (var tran = new SqlRTransaction())
            {
                string products = "";
                var query_orderDetail = Factory.CreateT_BAS_OrderDetails(tran);
                var list = query_orderDetail.GetList(a => a.OrderGuid == orderGuid, false, null, OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
                if (list == null || list.Count == 0) return "";
                foreach (var item in list)
                {
                    products += item.ProductName + ",";
                }
                return products.Substring(0, products.Length - 1);
            }
        }
        #endregion


        public static List<T_BAS_Products> GetProductsList(Guid? ProductCategoryGuid)
        {
            using (var query = Factory.CreateT_BAS_Products())
            {
                if (ProductCategoryGuid != Guid.Empty)
                {
                    return query.GetList(a => a.ProductCategoryGuid == ProductCategoryGuid && a.MerchantGuid == CurrentManage.MerchantGuid, true, a => a.Sort, DAL.Enums.OrderMethods.ASC, RFramework.SQLServer.Enums.LockType.Default);
                }
                else
                {
                    return null;
                }
            }
        }

        public static List<T_BAS_Products> GetCategoryList()
        {
            throw new NotImplementedException();
        }

        #region add by Panwp Diy

        /// <summary>
        /// 获取首页商品列表
        /// </summary>      
        public static List<T_BAS_Products> GetDIYProductsList(Guid[] categories, int pageNum)
        {
            if (categories == null || categories.Length <= 0) return new List<T_BAS_Products>();

            List<T_BAS_Products> list = null;
            using (var query = Factory.CreateT_BAS_Products())
            {
                list = query.GetList(m => m.IsPutaway == true && m.ProductCategoryGuid.SqlIn(categories) && m.MerchantGuid == CurrentManage.MerchantGuid, false, v => v.Sort);
            }
            if (list == null || list.Count <= 0) return new List<T_BAS_Products>();

            List<T_BAS_Products> products = new List<T_BAS_Products>();
            foreach (var category in categories)
            {
                var result = list.Where(m => m.ProductCategoryGuid == category).ToList();

                if (result.Count > 0)
                {
                    products.AddRange(result.Take(pageNum));
                }
            }

            return products;
        }

        public static List<T_BAS_Products> GetDIYProductsList(Guid categoryGuid, int productNum, int filter)
        {
            if (filter < 1 || filter > 6) return new List<T_BAS_Products>(0);

            if (productNum < 1 || productNum > 50) return new List<T_BAS_Products>(0);

            if (categoryGuid == Guid.Empty) return GetDIYAllProducts(productNum, filter);

            Expression<Func<T_BAS_Products, bool>> condition = m => m.IsPutaway == true && m.ProductCategoryGuid == categoryGuid && m.MerchantGuid == CurrentManage.MerchantGuid;
            QueryTranslator where = new QueryTranslator();
            string conditionString = where.Translate(condition);

            using (var query = Factory.CreateT_BAS_Products())
            {
                if (filter == 1)
                    return query.GetTopData(productNum.ToString(), conditionString, "SalesVolume + BaseSalesVolume", OrderMethods.DESC, LockType.Default, false);
                else if (filter == 2)
                    return query.GetTopData(productNum.ToString(), conditionString, "SalesVolume + BaseSalesVolume", OrderMethods.ASC, LockType.Default, false);
                else if (filter == 3)
                    return query.GetTopData(productNum.ToString(), conditionString, "Price", OrderMethods.DESC, LockType.Default, false);
                else if (filter == 4)
                    return query.GetTopData(productNum.ToString(), conditionString, "Price", OrderMethods.ASC, LockType.Default, false);
                else if (filter == 5)
                    return query.GetTopData(productNum.ToString(), conditionString, "Sort", OrderMethods.DESC, LockType.Default, false);
                else if (filter == 6)
                    return query.GetTopData(productNum.ToString(), conditionString, "Sort", OrderMethods.ASC, LockType.Default, false);
                else
                    return new List<T_BAS_Products>(0);
            }
        }

        public static PageList<R> GetDIYProductPageList<R>(GridModel gridModel, string name, Func<T_BAS_Products, R> selectorfield)
        {
            using (var sql = new SqlModel<T_BAS_Products>())
            {
                if (string.IsNullOrEmpty(name))
                    return sql.SqlPage(selectorfield, gridModel.page, gridModel.rows).SqlOrderBy(a => a.ProductGuid)
                              .SqlWhere(m => m.IsPutaway == true && m.MerchantGuid == CurrentManage.MerchantGuid)
                              .ToPageList();
                else
                    return sql.SqlPage(selectorfield, gridModel.page, gridModel.rows).SqlOrderBy(a => a.ProductGuid)
                          .SqlWhere(m => m.ProductName.SqlLike(name) && m.IsPutaway == true && m.MerchantGuid == CurrentManage.MerchantGuid)
                          .ToPageList();
            }
        }

        public static string GetProductImage(string path)
        {
            if (!string.IsNullOrEmpty(path) && path.IndexOf(".") > -1)
            {
                var fileExt = path.Substring(path.LastIndexOf("."));
                path = path.Replace(fileExt, "_thumbnail.jpg");
            }
            return path;
        }

        private static List<T_BAS_Products> GetDIYAllProducts(int productNum, int filter)
        {
            var categories = ProductCategorysManage.GetProductCategory();

            if (categories == null || categories.Count <= 0) return new List<T_BAS_Products>(0);

            var ids = categories.Select(m => m.ProductCategoryGuid).ToArray();
            List<T_BAS_Products> list = null;
            using (var query = Factory.CreateT_BAS_Products())
            {
                list = query.GetList(m => m.IsPutaway == true && m.ProductCategoryGuid.SqlIn(ids) && m.MerchantGuid == CurrentManage.MerchantGuid, false, v => v.ProductGuid, OrderMethods.ASC, LockType.Default, false);
            }
            var result = new List<T_BAS_Products>();
            foreach (var item in categories)
            {
                IEnumerable<T_BAS_Products> subList = null;

                if (filter == 1)
                    subList = list.Where(m => m.ProductCategoryGuid == item.ProductCategoryGuid).OrderByDescending(m => m.SalesVolume + m.BaseSalesVolume).Take(productNum);
                else if (filter == 2)
                    subList = list.Where(m => m.ProductCategoryGuid == item.ProductCategoryGuid).OrderBy(m => m.SalesVolume + m.BaseSalesVolume).Take(productNum);
                else if (filter == 3)
                    subList = list.Where(m => m.ProductCategoryGuid == item.ProductCategoryGuid).OrderByDescending(m => m.Price).Take(productNum);
                else if (filter == 4)
                    subList = list.Where(m => m.ProductCategoryGuid == item.ProductCategoryGuid).OrderBy(m => m.Price).Take(productNum);
                else if (filter == 5)
                    subList = list.Where(m => m.ProductCategoryGuid == item.ProductCategoryGuid).OrderByDescending(m => m.Sort).Take(productNum);
                else if (filter == 6)
                    subList = list.Where(m => m.ProductCategoryGuid == item.ProductCategoryGuid).OrderBy(m => m.Sort).Take(productNum);

                if (subList == null || subList.Count() <= 0) continue;

                result.AddRange(subList);
            }

            return result;
        }
        #endregion

        #region add by Panwp 重构

        public static PageList<T> GetProductPageList<T>(GridModel gridModel, string name, Guid? ptid, Func<T_BAS_Products, T> selectorfield)
        {
            using (var sql = new SqlModel<T_BAS_Products>())
            {
                return sql.SqlPage(selectorfield, gridModel.page, gridModel.rows)
                          .SqlOrderBy(a => a.ProductCode)
                          .SqlWhere(m => m.ProductName.SqlLike(name) && m.ProductCategoryGuid == ptid && m.MerchantGuid == CurrentManage.MerchantGuid, IsFilterNull: true)
                          .ToPageList();
            }
        }

        public static List<R> AvailableProducts<R>(Expression<Func<T_BAS_Products, T_BAS_ProductCategorys, R>> selectField)
        {
            using (var sql = new SqlModel<T_BAS_Products, T_BAS_ProductCategorys>())
            {
                return sql.SqlSelect(selectField)
                          .SqlJionLeft((a, b) => b).SqlOn((a, b) => a.ProductCategoryGuid == b.ProductCategoryGuid)
                          .SqlWhere((a, b) => a.MerchantGuid == Common.CurrentManage.MerchantGuid && a.IsPutaway == true)
                          .ToList();
            }
        }
        #endregion


    }
}
