using RFrameGenerate.Model;
using RFrameGenerate.Model.PageModel;
using RFramework.SQLServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using RFramework.SQLQuery;
using RFrameGenerate.DAL.Interface;
using RFrameGenerate.Common;

namespace RFrameGenerate.BLL
{
    public class ProductSKUManage
    {

        public static List<T_BAS_ProductType> GetPageList(Model.GridModel gridModel)
        {
            return null;
        }
        
        private static string GetSKUListState(List<T_BAS_ProductSKU> list, Guid? nameGuid, Guid valueGuid)
        {
            foreach (var item in list)
            {
                if (item.ProductSKUNameGuid == nameGuid && item.ProductSKUValueGuid == valueGuid)
                {
                    return "Checked";
                }
            }
            return "";
        }
        

        public static decimal GetSKUPrice(Guid productsGuid, int flag)
        {
            decimal price = 0m;
            using (var query = Factory.CreateT_BAS_ProductSKU())
            {
                var list = query.GetList(a => a.MerchantGuid == Common.CurrentManage.MerchantGuid && a.ProductGuid == productsGuid);
                if (list != null && list.Count > 0)
                {
                    switch (flag)
                    {
                        case 0:
                            price = list.Min(a => a.Price);
                            break;
                        case 1:
                            price = list.Max(a => a.Price);
                            break;
                    }
                }

            }
            return price;
        }


        public static List<PT_BAS_ProductSKU_GetProductSKUNameList> GetSKUNameList(Guid productsGuid)
        {

            if ((!MerchantManage.IsTop())&&(!MerchantManage.IsMarByMer(CurrentManage.MerchantGuid)))
            {
                using (var query = Factory.CreateT_BAS_ProductSKU())
                {
                    var listName = new List<PT_BAS_ProductSKU_GetProductSKUNameList>();
                    var list = query.GetList(c => c.ProductGuid == productsGuid && c.MerchantGuid == Common.CurrentManage.MerchantGuid, isFilterMerchant: false);
                    var g = list.OrderBy(c => c.Sort).GroupBy(c => c.ProductSKUGroupGuid).First();
                    var naList = g.OrderBy(c => c.ProductSKUNameGuid).ToList();

                    if (naList != null && naList.Count > 0)
                    {
                        naList.ForEach(c =>
                        {
                            listName.Add(new PT_BAS_ProductSKU_GetProductSKUNameList() { ProductSKUNameGuid = c.ProductSKUNameGuid.Value, Name = c.ProductSKUName });
                        });
                        return listName.ToList();
                    }
                }
            }

            using (var query = Factory.CreateProcedure())
            {

                return query.GetProductSKUNameList(productsGuid);

            }
        }


        public static decimal GetSKUInvenotory(Guid productsGuid)
        {
            using (var query = Factory.CreateProcedure())
            {
                return query.GetProductSKUInvenotory(productsGuid);
            }
        }

        public static List<PT_BAS_ProductSKU_GetProductSKUValueList> GetSubList(Guid productGuid, Guid productSKUNameGuid)
        {
            if ((!MerchantManage.IsTop()) && (!MerchantManage.IsMarByMer(CurrentManage.MerchantGuid)))
            {
                using (var query = Factory.CreateT_BAS_ProductSKU())
                {
                    var listValue = new List<PT_BAS_ProductSKU_GetProductSKUValueList>();
                    var list = query.GetList(c => c.ProductGuid == productGuid && c.ProductSKUNameGuid == productSKUNameGuid && c.MerchantGuid == Common.CurrentManage.MerchantGuid, false, c => c.Sort, DAL.Enums.OrderMethods.ASC, RFramework.SQLServer.Enums.LockType.Default, isFilterMerchant: false);
                    if (list != null && list.Count > 0)
                    {
                        list.ForEach(c =>
                        {
                            if (!listValue.Exists(v => v.ProductSKUValueGuid == c.ProductSKUValueGuid))
                            {
                                listValue.Add(new PT_BAS_ProductSKU_GetProductSKUValueList()
                                {
                                    ProductSKUNameGuid = c.ProductSKUNameGuid.Value,
                                    ProductSKUValue = c.ProductSKUValue,
                                    ProductSKUValueGuid = c.ProductSKUValueGuid.Value,
                                    Sort = c.Sort.Value,
                                });
                            }

                        });
                        return listValue.ToList();
                    }
                }
            }


            using (var query = Factory.CreateProcedure())
            {
                return query.GetProductSKUValueList(productGuid, productSKUNameGuid);
            }
        }



        public static Result GetProductInfo(string[] arrValus, Guid productGuid, ref PT_BAS_ProductSKU entity, ref  int integral)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    var query = Factory.CreateProcedure(tran);
                    var queryIntegral = Factory.CreateT_INT_IntegralRules(tran);
                    var list = query.GetProductSKUGroup(productGuid);
                    foreach (var item in list)
                    {
                        if (!string.IsNullOrEmpty(item.ProductSKUValueGuid))
                        {
                            var arrItems = item.ProductSKUValueGuid.Split(',');
                            string[] arrNewItems = new string[arrItems.Length];
                            for (int i = 0; i < arrItems.Length; i++)
                            {
                                arrNewItems[i] = arrItems[i].ToLower();
                            }
                            if (compareArr(arrValus, arrNewItems))
                            {

                                entity.ProductGuid = productGuid;
                                entity.GroupGuid = item.ProductSKUGroupGuid;
                                entity.Price = item.Price == null ? 0 : item.Price.Value;
                                entity.Inventory = item.Invenotory == null ? 0 : (int)Math.Round(item.Invenotory.Value, 0);
                                entity.ProductCode = item.Code;
                                entity.Sort = item.Sort == null ? 0 : item.Sort.Value;

                                //补充赠送积分 Bing 151218
                                var IntegralEntity = queryIntegral.GetFirstData(c => c.MerchantGuid == Common.CurrentManage.MerchantGuid);
                                IntegralRulesManage.GetIntegral(entity.Price, IntegralEntity, out integral);

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

        public static bool compareArr(string[] arrValus, string[] arrItems)
        {
            bool flag = arrValus.Intersect(arrItems).Count() == arrValus.Union(arrItems).Count();
            return flag;
        }

        public static decimal GetPrice(Guid groupGuid)
        {
            using (var query = Factory.CreateProcedure())
            {
                return query.GetPrice(groupGuid);
            }
        }



        public static List<PT_BAS_ProductSKU_GetSKUGroup> GetSkuGroupList(Guid groupGuid)
        {
            using (var query = Factory.CreateProcedure())
            {
                var list = query.PT_BAS_ProductSKU_GetSKUGroup(groupGuid);
                return list;
            }
        }


        public static string GetSkuGroup(Guid groupGuid)
        {
            string temp = "";
            using (var tran = new SqlRTransaction())
            {
                List<PT_BAS_ProductSKU_GetSKUGroup> list = new List<PT_BAS_ProductSKU_GetSKUGroup>();
                if (MerchantManage.IsTop() || MerchantManage.IsMarByMer(CurrentManage.MerchantGuid))
                {
                    var query = Factory.CreateProcedure(tran);
                    list = query.PT_BAS_ProductSKU_GetSKUGroup(groupGuid);
                }
                else
                {
                    var querySku = Factory.CreateT_BAS_ProductSKU(tran);
                    //补充下级规格获取
                    var listTemp = querySku.GetList(c => c.ProductSKUGroupGuid == groupGuid && c.MerchantGuid == Common.CurrentManage.MerchantGuid, false, c => c.Sort);
                    if (listTemp != null && listTemp.Count > 0)
                    {
                        listTemp.ForEach(c =>
                        {
                            list.Add(new PT_BAS_ProductSKU_GetSKUGroup() { Name = c.ProductSKUName, Value = c.ProductSKUValue });
                        });
                    }
                }
                if (list == null || list.Count == 0) return "";
                foreach (var item in list)
                {

                    temp += item.Name;
                    temp += ":\"";
                    temp += item.Value;
                    temp += "\",";
                }
                return temp.Substring(0, temp.Length - 1);
            }
        }

        public static Result GetSkuGroup(Guid groupGuid, ref string tips)
        {
            string temp = "";
            using (var tran = new SqlRTransaction())
            {
                List<PT_BAS_ProductSKU_GetSKUGroup> list = new List<PT_BAS_ProductSKU_GetSKUGroup>();
                if (MerchantManage.IsTop() || MerchantManage.IsMarByMer(CurrentManage.MerchantGuid))
                {
                    var query = Factory.CreateProcedure(tran);
                    list = query.PT_BAS_ProductSKU_GetSKUGroup(groupGuid);
                }
                else
                {
                    var querySku = Factory.CreateT_BAS_ProductSKU(tran);
                    var listTemp = querySku.GetList(c => c.ProductSKUGroupGuid == groupGuid && c.MerchantGuid == Common.CurrentManage.MerchantGuid, false, c => c.Sort);
                    if (listTemp != null && listTemp.Count > 0)
                    {
                        listTemp.ForEach(c =>
                        {
                            list.Add(new PT_BAS_ProductSKU_GetSKUGroup() { Name = c.ProductSKUName, Value = c.ProductSKUValue });
                        });
                    }
                }
                if (list == null || list.Count == 0) return new Result(false, "没有找到数据");
                foreach (var item in list)
                {
                    temp += item.Name;
                    temp += ":\"";
                    temp += item.Value;
                    temp += "\",";
                }
                tips = temp.Substring(0, temp.Length - 1);
                return new Result(true);
            }
        }

        /// <summary>
        /// 维护用
        /// </summary>
        /// <param name="groupGuid"></param>
        /// <returns></returns>
        public static string GetSkuGroupHelper(Guid groupGuid)
        {
            string temp = "";
            using (var query = Factory.CreateProcedure())
            {
                var list = query.PT_BAS_ProductSKU_GetSKUGroup_Helper(groupGuid);
                if (list.Count == 0) return "";
                foreach (var item in list)
                {

                    temp += item.Name;
                    temp += ":\"";
                    temp += item.Value;
                    temp += "\",";
                }
                return temp.Substring(0, temp.Length - 1);
            }
        }
        /// <summary>
        /// 导入商品复制规格(导入商品)
        /// </summary>
        /// <param name="lstProduct"></param>
        /// <returns></returns>
        public static Result CopySKUData(List<T_BAS_Products> lstProduct, SqlRTransaction 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_sku = Factory.CreateT_BAS_ProductSKU(tran);
            var query_products = Factory.CreateT_BAS_Products(tran);

            var addProductTypeList = new List<T_BAS_ProductType>();

            List<T_BAS_ProductSKUName> addProductSKUNameList = new List<T_BAS_ProductSKUName>();

            List<T_BAS_ProductSKUValue> addProductSKUValueList = new List<T_BAS_ProductSKUValue>();

            try
            {
                var topMerchantGuid = lstProduct.Select(a => a.SMerchantGuid).Distinct().FirstOrDefault();
                if (lstProduct == null || lstProduct.Count == 0) return new Result(false, "找不到商品数据！");

                var guid = lstProduct.Select(a => a.OriginalProductGuid).FirstOrDefault();

                //商品与商品规格
                foreach (var item in lstProduct)
                {
                    //原商品规格
                    var listSKU = query_sku.GetList(a => a.ProductGuid == guid && a.MerchantGuid == topMerchantGuid, isFilterMerchant: false);
                    //新增规格
                    foreach (var subitem in listSKU)
                    {
                        var skuname = GetProductSKUName(subitem.ProductSKUNameGuid, item.MerchantGuid.Value, addProductSKUNameList, query_skuName);
                        var skuvalue = GetProductSKUValue(subitem.ProductSKUValueGuid, item.MerchantGuid.Value, addProductSKUValueList, query_skuValue);
                        T_BAS_ProductSKU sku = new T_BAS_ProductSKU()
                        {
                            ProductSKUGuid = Guid.NewGuid(),
                            ProductGuid = item.ProductGuid,
                            ProductSKUNameGuid = skuname == null ? Guid.Empty : skuname.ProductSKUNameGuid,
                            ProductSKUValueGuid = skuvalue == null ? Guid.Empty : skuvalue.ProductSKUValueGuid,
                            MerchantGuid = item.MerchantGuid,
                            ProductSKUGroupGuid = subitem.ProductSKUGroupGuid,
                            Price = subitem.Price,
                            Invenotory = subitem.Invenotory,
                            Code = subitem.Code,
                            Weight = subitem.Weight,
                            Sort = subitem.Sort,
                            OriginalProductSKUGuid = subitem.ProductSKUGuid,
                            SMerchantGuid = item.MerchantGuid,
                            EntityState = EntityStates.ToBeAdd
                        };
                        query_sku.Add(sku);
                    }

                    var type = GetProductType(item.ProductTypeGuid, item.MerchantGuid.Value, addProductTypeList, query_productType);

                    if (type != null)
                    {
                        query_products.Update(a => new Object[] { a.ProductTypeGuid == type.ProductTypeGuid }, a => a.ProductGuid == item.ProductGuid && a.MerchantGuid == item.MerchantGuid, false);
                    }

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

        /// <summary>
        /// 导入商品复制规格(添加下级代理)
        /// </summary>
        /// <param name="lstProduct"></param>
        /// <returns></returns>
        public static Result CopySKUData(Guid? topAgentMerchantGuid, List<T_BAS_Products> lstProduct, SqlRTransaction 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_sku = Factory.CreateT_BAS_ProductSKU(tran);
            var query_products = Factory.CreateT_BAS_Products(tran);

            var addProductTypeList = new List<T_BAS_ProductType>();

            List<T_BAS_ProductSKUName> addProductSKUNameList = new List<T_BAS_ProductSKUName>();

            List<T_BAS_ProductSKUValue> addProductSKUValueList = new List<T_BAS_ProductSKUValue>();

            List<T_BAS_ProductSKU> list_SKU = new List<T_BAS_ProductSKU>();
            try
            {
                if (lstProduct == null || lstProduct.Count == 0) return new Result(false, "找不到商品数据！");
                //商品与商品规格
                foreach (var item in lstProduct)
                {
                    var guid = lstProduct.Select(a => a.OriginalProductGuid).FirstOrDefault();
                    //原商品规格
                    List<T_BAS_ProductSKU> list_sku = new List<T_BAS_ProductSKU>();
                    var listSKU = query_sku.GetList(a => a.ProductGuid == guid && a.MerchantGuid == topAgentMerchantGuid, isFilterMerchant: false);
                    //新增规格
                    foreach (var subitem in listSKU)
                    {
                        var skuname = GetProductSKUName(subitem.ProductSKUNameGuid, item.MerchantGuid.Value, addProductSKUNameList, query_skuName);
                        var skuvalue = GetProductSKUValue(subitem.ProductSKUValueGuid, item.MerchantGuid.Value, addProductSKUValueList, query_skuValue);
                        T_BAS_ProductSKU sku = new T_BAS_ProductSKU()
                        {
                            ProductSKUGuid = Guid.NewGuid(),
                            ProductGuid = item.ProductGuid,
                            ProductSKUNameGuid = skuname == null ? Guid.Empty : skuname.ProductSKUNameGuid,
                            ProductSKUValueGuid = skuvalue == null ? Guid.Empty : skuvalue.ProductSKUValueGuid,
                            MerchantGuid = item.MerchantGuid,
                            ProductSKUGroupGuid = subitem.ProductSKUGroupGuid,
                            Price = subitem.Price,
                            Invenotory = subitem.Invenotory,
                            Code = subitem.Code,
                            Weight = subitem.Weight,
                            Sort = subitem.Sort,
                            OriginalProductSKUGuid = subitem.ProductSKUGuid,
                            SMerchantGuid = item.MerchantGuid,
                            EntityState = EntityStates.ToBeAdd
                        };
                        list_sku.Add(sku);
                    }
                    query_sku.AddList(list_sku);
                    var type = GetProductType(item.ProductTypeGuid, item.MerchantGuid.Value, addProductTypeList, query_productType);

                    if (type != null)
                    {
                        query_products.Update(a => new Object[] { a.ProductTypeGuid == type.ProductTypeGuid }, a => a.ProductGuid == item.ProductGuid && a.MerchantGuid == item.MerchantGuid, false);
                    }

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


        /// <summary>
        /// 获取商品类型
        /// </summary>
        /// <param name="productTypeGuid">顶级商家商品类型Guid</param>
        /// <param name="merchantGuid">当前商家Guid</param>
        /// <param name="addList">商品类型Guid集合</param>
        /// <param name="dic">商品类型字典</param>
        /// <param name="query"></param>
        /// <returns></returns>
        public  static T_BAS_ProductType GetProductType(Guid? productTypeGuid, Guid merchantGuid, List<T_BAS_ProductType> addList, IQuery<T_BAS_ProductType> query)
        {
            if (productTypeGuid == null || productTypeGuid == Guid.Empty) return null;
            if (addList != null && addList.Count > 0)
            {
                var type = addList.FirstOrDefault(m => m.OriginalProductTypeGuid == productTypeGuid && m.MerchantGuid == merchantGuid);

                if (type != null) return type;
            }

            var productType = query.GetFirstData(m => m.OriginalProductTypeGuid == productTypeGuid && m.MerchantGuid == merchantGuid, isFilterMerchant: false);

            if (productType == null) productType = new T_BAS_ProductType();

            return productType.ProductTypeGuid == Guid.Empty ? null : productType;
        }
        /// <summary>
        /// 获取规格名称
        /// </summary>
        /// <param name="productSKUNameGuid">顶级商家规格名称</param>
        /// <param name="merchantGuid">当前商家Guid</param>
        /// <param name="addList">规格名称集合</param>
        /// <param name="dic">规格名称字典</param>
        /// <param name="query"></param>
        /// <returns></returns>
        public static T_BAS_ProductSKUName GetProductSKUName(Guid? productSKUNameGuid, Guid merchantGuid, List<T_BAS_ProductSKUName> addList, IQuery<T_BAS_ProductSKUName> query)
        {
            if (productSKUNameGuid == null || productSKUNameGuid == Guid.Empty) return null;
            if (addList != null && addList.Count > 0)
            {
                var name = addList.FirstOrDefault(a => a.OriginalProductSKUNameGuid == productSKUNameGuid && a.MerchantGuid == merchantGuid);
                if (name != null) return name;
            }

            var productSKUName = query.GetFirstData(a => a.OriginalProductSKUNameGuid == productSKUNameGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);


            if (productSKUName == null) productSKUName = new T_BAS_ProductSKUName();

            return productSKUName.ProductSKUNameGuid == Guid.Empty ? null : productSKUName;
        }

        /// <summary>
        /// 获取规格值
        /// </summary>
        /// <param name="productSKUNameGuid">顶级商家规格值</param>
        /// <param name="merchantGuid">当前商家Guid</param>
        /// <param name="addList">规格值集合</param>
        /// <param name="dic">规格值字典</param>
        /// <param name="query"></param>
        /// <returns></returns>
        public static T_BAS_ProductSKUValue GetProductSKUValue(Guid? productSKUValueGuid, Guid merchantGuid, List<T_BAS_ProductSKUValue> addList, IQuery<T_BAS_ProductSKUValue> query)
        {
            if (productSKUValueGuid == null || productSKUValueGuid == Guid.Empty) return null;
            if (addList != null && addList.Count > 0)
            {
                var value = addList.FirstOrDefault(a => a.OriginalProductSKUValueGuid == productSKUValueGuid && a.MerchantGuid == merchantGuid);
                if (value != null) return value;
            }

            var productSKUValue = query.GetFirstData(a => a.OriginalProductSKUValueGuid == productSKUValueGuid && a.MerchantGuid == merchantGuid, isFilterMerchant: false);

            if (productSKUValue == null) productSKUValue = new T_BAS_ProductSKUValue();

            return productSKUValue.ProductSKUValueGuid == Guid.Empty ? null : productSKUValue;
        }

    }


}
