using Mall.Model.Extend.Product;
using Mall.Repository.Product;
using System.Collections.Generic;
using VT.FW.DB;
using System.Linq;
using Mall.Model.Entity.Product;
using Mall.AOP.CustomerAttribute;
using System;

namespace Mall.Module.Product
{
    /// <summary>
    /// 拼团活动处理类
    /// </summary>
    public class GroupBuyActivityModule
    {
        /// <summary>
        /// 拼团活动仓储层对象
        /// </summary>
        private readonly RB_Groupbuy_ActivityRepository groupbuy_ActivityRepository = new RB_Groupbuy_ActivityRepository();

        /// <summary>
        /// 拼团活动商品规格价格仓储层对象
        /// </summary>
        private RB_Groupbuy_Activity_SpecificationPriceRepository groupbuy_Activity_SpecificationPriceRepository = new RB_Groupbuy_Activity_SpecificationPriceRepository();

        /// <summary>
        /// 拼团活动商品关联规格值仓储层对象
        /// </summary>
        private RB_Groupbuy_Activity_SpecificationValueRepository groupbuy_Activity_SpecificationValueRepository = new RB_Groupbuy_Activity_SpecificationValueRepository();

        /// <summary>
        /// 拼团商品关联规格仓储层对象
        /// </summary>
        private RB_Groupbuy_Activity_SpecificationRepository groupbuy_Activity_SpecificationRepository = new RB_Groupbuy_Activity_SpecificationRepository();

        /// <summary>
        /// 阶梯团仓储层对象
        /// </summary>
        private RB_Groupbuy_Activity_StepRepository stepRepository = new RB_Groupbuy_Activity_StepRepository();

        /// <summary>
        /// 拼团活动商品阶梯价格仓储层对象
        /// </summary>
        private RB_Groupbuy_Activity_Step_PriceRepository groupbuy_Activity_Step_PriceRepository = new RB_Groupbuy_Activity_Step_PriceRepository();

        /// <summary>
        /// 拼团活动商品关联分销佣金表仓储对象
        /// </summary>
        private RB_GroupBuy_DistributioncommissionRepository groupBuy_DistributioncommissionRepository = new RB_GroupBuy_DistributioncommissionRepository();

        /// <summary>
        /// 拼团活动商品关联会员价格表仓储对象
        /// </summary>
        private RB_Groupbuy_MemberpriceRepository groupbuy_MemberpriceRepository = new RB_Groupbuy_MemberpriceRepository();


        /// <summary>
        /// 获取拼团活动商品分销佣金
        /// </summary>
        /// <returns></returns>
        public List<RB_Groupbuy_Memberprice_Extend> GetGroupBuyMemberpriceModule(RB_Groupbuy_Memberprice_Extend query)
        {
            return groupbuy_MemberpriceRepository.GetGroupBuyMemberpriceRepository(query);
        }

        /// <summary>
        /// 获取拼团活动商品分销佣金
        /// </summary>
        /// <returns></returns>
        public List<RB_GroupBuy_Distributioncommission_Extend> GetGroupBuyCommissionRepository(RB_GroupBuy_Distributioncommission_Extend query)
        {
            return groupBuy_DistributioncommissionRepository.GetGroupBuyCommissionRepository(query);
        }


        /// <summary>
        /// 获取拼团活动商品规格价格列表
        /// </summary>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Groupbuy_Activity_Step_Price_Extend> GetGroupbuyActivitySpecificationpriceListModule(RB_Groupbuy_Activity_Step_Price_Extend query)
        {
            return groupbuy_Activity_Step_PriceRepository.GetGroupbuyActivitySpecificationpriceListRepository(query);
        }

        /// <summary>
        /// 获取拼团活动阶梯价列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Groupbuy_Activity_Step_Extend> GetGroupBuyActivityListModule(RB_Groupbuy_Activity_Step_Extend query)
        {
            return stepRepository.GetGroupBuyActivityListRepository(query);
        }

        /// <summary>
        /// 获取拼团活动商品规格价格列表
        /// </summary>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Groupbuy_Activity_Specificationprice_Extend> GetGroupbuyActivitySpecificationpriceListModule(RB_Groupbuy_Activity_Specificationprice_Extend dmodel)
        {
            return groupbuy_Activity_SpecificationPriceRepository.GetGroupbuyActivitySpecificationpriceListRepository(dmodel);
        }

        /// <summary>
        /// 获取拼团活动商品关联规格值列表
        /// </summary>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Groupbuy_Activity_Specificationvalue_Extend> GetGroupbuyActivitySpecificationValueListModule(RB_Groupbuy_Activity_Specificationvalue_Extend dmodel)
        {
            return groupbuy_Activity_SpecificationValueRepository.GetGroupbuyActivitySpecificationValueListRepository(dmodel);
        }

        /// <summary>
        /// 获取拼团商品关联规格列表
        /// </summary>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Groupbuy_Activity_Specification_Extend> GetGroupbuyActivitySpecificationListModule(RB_Groupbuy_Activity_Specification_Extend dmodel)
        {
            return groupbuy_Activity_SpecificationRepository.GetGroupbuyActivitySpecificationListRepository(dmodel);
        }


        /// <summary>
        ///  获取拼团活动分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowsCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Groupbuy_Activity_Extend> GetGroupbuyActivityPageListModule(int pageIndex, int pageSize, out long rowsCount, RB_Groupbuy_Activity_Extend query)
        {
            var list = groupbuy_ActivityRepository.GetGroupbuyActivityPageListRepository(pageIndex, pageSize, out rowsCount, query);
            if (list != null && list.Count > 0)
            {
                string Ids = string.Join(",", list.Select(qitem => qitem.GoodId));
                //拼团阶梯基础设置列表
                List<RB_Groupbuy_Activity_Step_Extend> groupStepList = GetGroupBuyActivityListModule(new RB_Groupbuy_Activity_Step_Extend()
                {
                    MallBaseId = query.MallBaseId,
                    TenantId = query.TenantId,
                    GoodIds = Ids,
                });
                //拼团阶梯价格设置列表
                List<RB_Groupbuy_Activity_Step_Price_Extend> StepPriceList = GetGroupbuyActivitySpecificationpriceListModule(new RB_Groupbuy_Activity_Step_Price_Extend()
                {
                    MallBaseId = query.MallBaseId,
                    TenantId = query.TenantId,
                    GoodsIds = Ids,
                });

                if (groupStepList != null && groupStepList.Count > 0)
                {
                    foreach (var item in groupStepList)
                    {
                        item.StepPriceList = StepPriceList?.Where(qitem => qitem.GoodId == item.GoodId && qitem.StepId == item.StepId)?.ToList() ?? new List<RB_Groupbuy_Activity_Step_Price_Extend>();
                    }
                }
                foreach (var item in list)
                {
                    item.GroupList = groupStepList?.Where(qitem => qitem.GoodId == item.GoodId)?.ToList() ?? new List<RB_Groupbuy_Activity_Step_Extend>();
                }
            }
            return list;
        }

        /// <summary>
        /// 获取活动实体类
        /// </summary>
        /// <param name="query"></param>
        /// <param name="isGetSpec">是否获取规格信息</param>
        /// <returns></returns>
        public RB_Groupbuy_Activity_Extend GetGroupbuyActivityEntityModule(RB_Groupbuy_Activity_Extend query, bool isGetSpec = false)
        {
            var extModel = groupbuy_ActivityRepository.GetGroupbuyActivityEntityRepository(query);
            if (extModel == null)
            {
                extModel = new RB_Groupbuy_Activity_Extend();
            }
            if (!string.IsNullOrWhiteSpace(extModel.GoodsService))
            {
                extModel.ServiceList = Common.Plugin.JsonHelper.DeserializeObject<List<RB_ImageCommonModel>>(extModel.GoodsService);
            }
            if (isGetSpec)
            {
                //获取规格列表
                List<RB_Groupbuy_Activity_Specification_Extend> specificationList = GetGroupbuyActivitySpecificationListModule(new RB_Groupbuy_Activity_Specification_Extend()
                {
                    MallBaseId = query.MallBaseId,
                    TenantId = query.TenantId,
                    GoodsId = extModel.GoodId,
                });

                //规格值列表
                List<RB_Groupbuy_Activity_Specificationvalue_Extend> specificationvalueList = GetGroupbuyActivitySpecificationValueListModule(new RB_Groupbuy_Activity_Specificationvalue_Extend()
                {
                    MallBaseId = query.MallBaseId,
                    TenantId = query.TenantId,
                    GoodsId = extModel.GoodId,
                });
                if (specificationList != null && specificationList.Count > 0)
                {
                    foreach (var item in specificationList)
                    {
                        item.SpecificationValueList = specificationvalueList?.Where(qitem => qitem.SpecificationId == item.Id)?.ToList() ?? new List<RB_Groupbuy_Activity_Specificationvalue_Extend>();
                    }
                }
                //规格价格列表
                List<RB_Groupbuy_Activity_Specificationprice_Extend> specPriceList = GetGroupbuyActivitySpecificationpriceListModule(new RB_Groupbuy_Activity_Specificationprice_Extend()
                {
                    MallBaseId = query.MallBaseId,
                    TenantId = query.TenantId,
                    GoodsId = extModel.GoodId,
                });
                if (specPriceList != null && specPriceList.Count > 0)
                {
                    foreach (var item in specPriceList)
                    {
                        int SortNum = 1;
                        if (!string.IsNullOrEmpty(item.SpecificationSort))
                        {
                            item.AttrList = GetGroupBuyGoodsAttr(item.SpecificationSort, specificationList); ;
                        }
                        item.SortNum = SortNum;
                        SortNum++;
                    }
                }

                //拼团阶梯基础设置列表
                List<RB_Groupbuy_Activity_Step_Extend> groupStepList = GetGroupBuyActivityListModule(new RB_Groupbuy_Activity_Step_Extend()
                {
                    MallBaseId = query.MallBaseId,
                    TenantId = query.TenantId,
                    GoodId = extModel.GoodId,
                });
                //拼团阶梯价格设置列表
                List<RB_Groupbuy_Activity_Step_Price_Extend> StepPriceList = GetGroupbuyActivitySpecificationpriceListModule(new RB_Groupbuy_Activity_Step_Price_Extend()
                {
                    MallBaseId = query.MallBaseId,
                    TenantId = query.TenantId,
                    GoodId = extModel.GoodId,
                });

                //分销佣金列表
                List<RB_GroupBuy_Distributioncommission_Extend> commissionList = GetGroupBuyCommissionRepository(new RB_GroupBuy_Distributioncommission_Extend()
                {
                    MallBaseId = query.MallBaseId,
                    TenantId = query.TenantId,
                    GoodsId = extModel.GoodId,
                });
                //会员价设置列表
                List<RB_Groupbuy_Memberprice_Extend> memberpriceList = GetGroupBuyMemberpriceModule(new RB_Groupbuy_Memberprice_Extend()
                {
                    MallBaseId = query.MallBaseId,
                    TenantId = query.TenantId,
                    GoodsId = extModel.GoodId,
                });

                if (groupStepList != null && groupStepList.Count > 0)
                {
                    foreach (var item in groupStepList)
                    {
                        item.StepPriceList = StepPriceList?.Where(qitem => qitem.StepId == item.StepId)?.ToList() ?? new List<RB_Groupbuy_Activity_Step_Price_Extend>();
                        foreach (var subItem in item.StepPriceList)
                        {
                            int SortNum = 1;
                            if (!string.IsNullOrEmpty(subItem.SpecificationSort))
                            {
                                subItem.AttrList = GetGroupBuyGoodsAttr(subItem.SpecificationSort, specificationList);
                            }
                            subItem.SortNum = SortNum;
                            SortNum++;
                        }
                        //分销普通类型
                        if (extModel.SeparateDistributionType == 1)
                        {
                            item.DistributioncommissionList = commissionList?.Where(qitem => qitem.StepId == item.StepId)?.ToList() ?? new List<RB_GroupBuy_Distributioncommission_Extend>();
                        }
                        //分销详细设置
                        else if (extModel.SeparateDistributionType == 2)
                        {
                            item.DistributionCommissionTreeList = new List<RB_GroupBuy_Distributioncommission_Extend>();
                            var gradeList = commissionList.Where(qitem => qitem.StepId == item.StepId).GroupBy(qitem => new { qitem.SpecificationSort, qitem.StepId }).ToList();
                            foreach (var subItem in gradeList)
                            {
                                var tempModel = commissionList.Where(qitem => qitem.StepId == subItem.Key.StepId && qitem.SpecificationSort == subItem.Key.SpecificationSort).FirstOrDefault();
                                item.DistributionCommissionTreeList.Add(new RB_GroupBuy_Distributioncommission_Extend()
                                {
                                    SpecificationSort = tempModel.SpecificationSort,
                                    GradeCommissionList =
                                    commissionList.Where(qitem => qitem.StepId == subItem.Key.StepId && qitem.SpecificationSort == subItem.Key.SpecificationSort)
                                    .OrderBy(qitem => qitem.DistributorGrade).ToList()
                                });
                            }
                            foreach (var subItem in item.DistributionCommissionTreeList)
                            {
                                if (!string.IsNullOrWhiteSpace(subItem.SpecificationSort))
                                {
                                    subItem.AttrList = GetGroupBuyGoodsAttr(subItem.SpecificationSort, specificationList);
                                }
                            }
                        }

                        //会员价设置
                        item.MemberpriceList = new List<RB_Groupbuy_Memberprice_Extend>();
                        var gradeMemberList = memberpriceList.Where(qitem => qitem.StepId == item.StepId).GroupBy(qitem => new { qitem.SpecificationSort, qitem.StepId }).ToList();
                        foreach (var subItem in gradeMemberList)
                        {
                            var tempModel = memberpriceList.Where(qitem => qitem.StepId == subItem.Key.StepId && qitem.SpecificationSort == subItem.Key.SpecificationSort).FirstOrDefault();
                            item.MemberpriceList.Add(new RB_Groupbuy_Memberprice_Extend()
                            {
                                SpecificationSort = tempModel.SpecificationSort,
                                GradeMemberPriceList =
                                memberpriceList.Where(qitem => qitem.StepId == subItem.Key.StepId && qitem.SpecificationSort == subItem.Key.SpecificationSort)
                                .OrderBy(qitem => qitem.MemberGrade).ToList()
                            });
                        }
                        foreach (var subItem in item.MemberpriceList)
                        {
                            if (!string.IsNullOrWhiteSpace(subItem.SpecificationSort))
                            {
                                subItem.AttrList = GetGroupBuyGoodsAttr(subItem.SpecificationSort, specificationList);
                            }
                        }
                    }
                }
                extModel.SpecificationList = specificationList;
                extModel.SpecificationPriceList = specPriceList;
                extModel.GroupList = groupStepList;
            }
            return extModel;
        }

        /// <summary>
        /// 获取拼团商品的商品规格属性
        /// </summary>
        /// <param name="SpecificationSort">商品规格</param>
        /// <param name="specificationList">规格值</param>
        /// <returns></returns>
        public List<object> GetGroupBuyGoodsAttr(string SpecificationSort, List<RB_Groupbuy_Activity_Specification_Extend> specificationList)
        {
            List<object> AttrList = new List<object>();
            if (!string.IsNullOrEmpty(SpecificationSort))
            {
                var ssarr = SpecificationSort.Split(':');
                int Sort = Convert.ToInt32(ssarr[0]);
                string pic_url = specificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                for (int i = 0; i < ssarr.Length; i++)
                {
                    var smodel = specificationList[i];
                    var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                    AttrList.Add(new
                    {
                        SName = smodel.Name,
                        SId = smodel.Id,
                        SVId = svmodel.Sort,
                        SVName = svmodel.Name
                    });
                }
            }
            return AttrList;
        }

        /// <summary>
        /// 新增修改拼团活动
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetGroupbuyActivityModule(RB_Groupbuy_Activity_Extend extModel)
        {
            bool flag = false;
            
            var oldModel = GetGroupbuyActivityEntityModule(new RB_Groupbuy_Activity_Extend() { ActivityId=extModel.ActivityId}, isGetSpec: false);
            int oldSeparateDistributionType = 0;
            if (oldModel != null )
            {
                oldSeparateDistributionType = oldModel?.SeparateDistributionType??0;
            }
            if (extModel.ActivityId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Groupbuy_Activity_Extend.StartTime),extModel.StartTime},
                    { nameof(RB_Groupbuy_Activity_Extend.EndTime),extModel.EndTime},
                    { nameof(RB_Groupbuy_Activity_Extend.GoodId),extModel.GoodId},
                    { nameof(RB_Groupbuy_Activity_Extend.GoodsStatus),extModel.GoodsStatus},
                    { nameof(RB_Groupbuy_Activity_Extend.SellingPrice),extModel.SellingPrice},
                    { nameof(RB_Groupbuy_Activity_Extend.Original_Price),extModel.Original_Price},
                    { nameof(RB_Groupbuy_Activity_Extend.Goods_Stock),extModel.Goods_Stock},
                    { nameof(RB_Groupbuy_Activity_Extend.Goods_unit),extModel.Goods_unit},
                    { nameof(RB_Groupbuy_Activity_Extend.Goods_no),extModel.Goods_no},
                    { nameof(RB_Groupbuy_Activity_Extend.Goods_weight),extModel.Goods_weight},
                    { nameof(RB_Groupbuy_Activity_Extend.Sort),extModel.Sort},
                    { nameof(RB_Groupbuy_Activity_Extend.Is_Auto_Add_Robot),extModel.Is_Auto_Add_Robot},
                    { nameof(RB_Groupbuy_Activity_Extend.Virtual_Sales),extModel.Virtual_Sales},
                    { nameof(RB_Groupbuy_Activity_Extend.Is_Alone_Buy),extModel.Is_Alone_Buy},
                    { nameof(RB_Groupbuy_Activity_Extend.IsDefaultService),extModel.IsDefaultService},
                    { nameof(RB_Groupbuy_Activity_Extend.GoodsService),extModel.GoodsService},
                    { nameof(RB_Groupbuy_Activity_Extend.FreightId),extModel.FreightId},
                    { nameof(RB_Groupbuy_Activity_Extend.FormsId),extModel.FormsId},
                    { nameof(RB_Groupbuy_Activity_Extend.Confine_Count),extModel.Confine_Count},
                    { nameof(RB_Groupbuy_Activity_Extend.Confine_Order_Count),extModel.Confine_Order_Count},
                    { nameof(RB_Groupbuy_Activity_Extend.Pieces),extModel.Pieces},
                    { nameof(RB_Groupbuy_Activity_Extend.Forehead),extModel.Forehead},
                    { nameof(RB_Groupbuy_Activity_Extend.Is_Area_Limit),extModel.Is_Area_Limit},
                    { nameof(RB_Groupbuy_Activity_Extend.Area_limit),extModel.Area_limit},
                    { nameof(RB_Groupbuy_Activity_Extend.Is_quick_shop),extModel.Is_quick_shop},
                    { nameof(RB_Groupbuy_Activity_Extend.Give_integral),extModel.Give_integral},
                    { nameof(RB_Groupbuy_Activity_Extend.Give_integral_type),extModel.Give_integral_type},
                    { nameof(RB_Groupbuy_Activity_Extend.Is_forehead_integral),extModel.Is_forehead_integral},
                    { nameof(RB_Groupbuy_Activity_Extend.Forehead_integral_type),extModel.Forehead_integral_type},
                    { nameof(RB_Groupbuy_Activity_Extend.Accumulative),extModel.Accumulative},
                    { nameof(RB_Groupbuy_Activity_Extend.CardIds),extModel.CardIds},
                    { nameof(RB_Groupbuy_Activity_Extend.App_share_title),extModel.App_share_title},
                    { nameof(RB_Groupbuy_Activity_Extend.App_share_pic),extModel.App_share_pic},
                    { nameof(RB_Groupbuy_Activity_Extend.IsCustomSpecification),extModel.IsCustomSpecification},
                    { nameof(RB_Groupbuy_Activity_Extend.SeparateDistribution),extModel.SeparateDistribution},
                    { nameof(RB_Groupbuy_Activity_Extend.SeparateDistributionType),extModel.SeparateDistributionType},
                    { nameof(RB_Groupbuy_Activity_Extend.SeparateDistributionMoneyType),extModel.SeparateDistributionMoneyType},
                    { nameof(RB_Groupbuy_Activity_Extend.EnjoyMember),extModel.EnjoyMember},
                    { nameof(RB_Groupbuy_Activity_Extend.SeparateSetMember),extModel.SeparateSetMember},
                };
                flag = groupbuy_ActivityRepository.Update(fileds, new WhereHelper(nameof(RB_Groupbuy_Activity_Extend.ActivityId), extModel.ActivityId));
            }
            else
            {
                var newId = groupbuy_ActivityRepository.Insert(extModel);
                extModel.ActivityId = newId;
                flag = newId > 0;
            }
            if (flag)
            {
                flag = SetGoodsSpecificationModule(extModel, out bool isChange);
                flag = SetGoodGroupStepModule(extModel, isChange, oldSeparateDistributionType);
            }
            return flag;
        }

        /// <summary>
        /// 添加修改商品规格
        /// </summary>
        /// <param name="extModel"></param>
        /// <param name="isChange">是否规格有改变</param>
        /// <returns></returns>
        private bool SetGoodsSpecificationModule(RB_Groupbuy_Activity_Extend extModel, out bool isChange)
        {
            isChange = false;
            bool flag = true;
            var old_SpecificationList = groupbuy_Activity_SpecificationRepository.GetGroupbuyActivitySpecificationListRepository(
                new RB_Groupbuy_Activity_Specification_Extend() { GoodsId = extModel.GoodId, TenantId = extModel.TenantId, MallBaseId = extModel.MallBaseId });
            if (extModel.IsCustomSpecification == 1)
            {
                //判断规格条数是否变动
                if (old_SpecificationList.Count() != extModel.SpecificationList.Count() || old_SpecificationList.Count() != extModel.SpecificationList.Where(x => x.Id > 0).Count())
                {
                    isChange = true;
                    //删除规格
                    groupbuy_Activity_SpecificationRepository.Delete(new WhereHelper(nameof(RB_Groupbuy_Activity_Specification_Extend.GoodsId), extModel.GoodId));
                    //删除规格值
                    groupbuy_Activity_SpecificationValueRepository.Delete(new WhereHelper(nameof(RB_Groupbuy_Activity_Specificationvalue_Extend.GoodsId), extModel.GoodId));
                    //删除规格价格
                    groupbuy_Activity_SpecificationPriceRepository.Delete(new WhereHelper(nameof(RB_Groupbuy_Activity_Specificationprice_Extend.GoodsId), extModel.GoodId));

                    //新增规格和规格值
                    foreach (var specItem in extModel.SpecificationList)
                    {
                        //新增规格
                        var specModel = new RB_Groupbuy_Activity_Specification_Extend()
                        {
                            CreateDate = DateTime.Now,
                            EnabledImage = specItem.EnabledImage,
                            GoodsId = extModel.GoodId,
                            Id = 0,
                            TenantId = extModel.TenantId,
                            MallBaseId = extModel.MallBaseId,
                            Status = 0,
                            Name = specItem.Name,
                            Sort = specItem.Sort,
                        };

                        var newSpecId = groupbuy_Activity_SpecificationRepository.Insert(specModel);
                        specModel.Id = newSpecId;
                        flag = newSpecId > 0;

                        //新增规格值
                        if (specItem.SpecificationValueList != null && specItem.SpecificationValueList.Count > 0)
                        {
                            foreach (var specValueItem in specItem.SpecificationValueList)
                            {
                                var specValueModel = new RB_Groupbuy_Activity_Specificationvalue_Extend()
                                {
                                    MallBaseId = extModel.MallBaseId,
                                    TenantId = extModel.TenantId,
                                    SpecificationId = specModel.Id,
                                    GoodsId = extModel.GoodId,
                                    CreateDate = DateTime.Now,
                                    Status = 0,
                                    Id = 0,
                                    Image = specValueItem.Image,
                                    Name = specValueItem.Name,
                                    Sort = specValueItem.Sort,
                                };
                                var specValueId = groupbuy_Activity_SpecificationValueRepository.Insert(specValueModel);
                                specValueModel.Id = specValueId;
                                flag = specValueId > 0;
                            }
                        }
                    }

                    //新增规格价格
                    foreach (var priceItem in extModel.SpecificationPriceList)
                    {
                        var priceModel = new RB_Groupbuy_Activity_Specificationprice_Extend()
                        {
                            Id = 0,
                            MallBaseId = extModel.MallBaseId,
                            TenantId = extModel.TenantId,
                            GoodsId = extModel.GoodId,
                            Status = 0,
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            GoodsNumbers = priceItem.GoodsNumbers,
                            GoodsWeight = priceItem.GoodsWeight,
                            InventoryNum = priceItem.InventoryNum,
                            SellingPrice = priceItem.SellingPrice,
                            SpecificationSort = priceItem.SpecificationSort,
                            Commission = priceItem.Commission,
                            CostMoney = priceItem.CostMoney
                        };
                        flag = groupbuy_Activity_SpecificationPriceRepository.Insert(priceModel) > 0;
                    }
                }
                else
                {
                    var specValuelist = groupbuy_Activity_SpecificationValueRepository.GetGroupbuyActivitySpecificationValueListRepository(new RB_Groupbuy_Activity_Specificationvalue_Extend() { GoodsId = extModel.GoodId, TenantId = extModel.TenantId, MallBaseId = extModel.MallBaseId });
                    var specPricelist = groupbuy_Activity_SpecificationPriceRepository.GetGroupbuyActivitySpecificationpriceListRepository(new RB_Groupbuy_Activity_Specificationprice_Extend() { GoodsId = extModel.GoodId, TenantId = extModel.TenantId, MallBaseId = extModel.MallBaseId });
                    foreach (var item in old_SpecificationList)
                    {
                        var supmodel = extModel.SpecificationList.Where(x => x.Id == item.Id).FirstOrDefault();
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>()
                        {
                            { nameof(RB_Goods_Specification.EnabledImage),supmodel.EnabledImage},
                            { nameof(RB_Goods_Specification.Name),supmodel.Name},
                            { nameof(RB_Goods_Specification.Sort),supmodel.Sort}
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>()
                        {
                            new WhereHelper()
                            {
                                FiledName=nameof(RB_Goods_Specification.Id),
                                FiledValue=item.Id,
                                OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        flag = groupbuy_Activity_SpecificationRepository.Update(keyValues1, wheres1);
                        if (flag)
                        {
                            var sv2list = specValuelist.Where(x => x.SpecificationId == item.Id).ToList();
                            if (sv2list.Count() != supmodel.SpecificationValueList.Count() || sv2list.Count() != supmodel.SpecificationValueList.Where(x => x.Id > 0).Count())
                            {
                                isChange = true;
                                groupbuy_Activity_SpecificationValueRepository.Delete(new WhereHelper(nameof(RB_Groupbuy_Activity_Specificationvalue_Extend.GoodsId), extModel.GoodId));
                                foreach (var specValueItem in supmodel.SpecificationValueList)
                                {
                                    flag = groupbuy_Activity_SpecificationValueRepository.Insert(new RB_Groupbuy_Activity_Specificationvalue_Extend()
                                    {
                                        MallBaseId = extModel.MallBaseId,
                                        TenantId = extModel.TenantId,
                                        SpecificationId = supmodel.Id,
                                        GoodsId = extModel.GoodId,
                                        CreateDate = DateTime.Now,
                                        Status = 0,
                                        Id = 0,
                                        Image = specValueItem.Image,
                                        Name = specValueItem.Name,
                                        Sort = specValueItem.Sort,
                                    }) > 0;
                                }
                            }
                            else
                            {
                                foreach (var qitem in sv2list)
                                {
                                    var supModel1 = supmodel.SpecificationValueList.Where(x => x.Id == qitem.Id).FirstOrDefault();
                                    Dictionary<string, object> keyValues2 = new Dictionary<string, object>()
                                    {
                                        { nameof(RB_Goods_SpecificationValue.Image),supModel1.Image},
                                        { nameof(RB_Goods_SpecificationValue.Name),supModel1.Name},
                                        { nameof(RB_Goods_SpecificationValue.Sort),supModel1.Sort}
                                    };
                                    List<WhereHelper> wheres2 = new List<WhereHelper>()
                                    {
                                        new WhereHelper()
                                        {
                                            FiledName=nameof(RB_Goods_Specification.Id),
                                            FiledValue=qitem.Id,
                                            OperatorEnum=OperatorEnum.Equal
                                        }
                                    };
                                    flag = groupbuy_Activity_SpecificationValueRepository.Update(keyValues2, wheres2);
                                }
                            }
                        }
                    }

                    //规格价格处理
                    if (specPricelist.Count() != extModel.SpecificationPriceList.Count() || specPricelist.Count() != extModel.SpecificationPriceList.Where(x => specPricelist.Select(y => y.SpecificationSort).Contains(x.SpecificationSort)).Count())
                    {
                        isChange = true;
                        //删除规格价格
                        groupbuy_Activity_SpecificationPriceRepository.Delete(new WhereHelper(nameof(RB_Groupbuy_Activity_Specificationprice_Extend.GoodsId), extModel.GoodId));
                        foreach (var priceItem in extModel.SpecificationPriceList)
                        {
                            var priceModel = new RB_Groupbuy_Activity_Specificationprice_Extend()
                            {
                                Id = 0,
                                MallBaseId = extModel.MallBaseId,
                                TenantId = extModel.TenantId,
                                GoodsId = extModel.GoodId,
                                Status = 0,
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                GoodsNumbers = priceItem.GoodsNumbers,
                                GoodsWeight = priceItem.GoodsWeight,
                                InventoryNum = priceItem.InventoryNum,
                                SellingPrice = priceItem.SellingPrice,
                                SpecificationSort = priceItem.SpecificationSort,
                                Commission = priceItem.Commission,
                                CostMoney = priceItem.CostMoney
                            };
                            flag = groupbuy_Activity_SpecificationPriceRepository.Insert(priceModel) > 0;
                        }
                    }
                    else
                    {
                        foreach (var item in specPricelist)
                        {
                            var pupmodel = extModel.SpecificationPriceList.Where(x => x.SpecificationSort == item.SpecificationSort).FirstOrDefault();
                            if (item.Commission != pupmodel.Commission || item.CostMoney != pupmodel.CostMoney || item.SellingPrice != pupmodel.SellingPrice || item.InventoryNum != pupmodel.InventoryNum || item.GoodsNumbers != pupmodel.GoodsNumbers || item.GoodsWeight != pupmodel.GoodsWeight)
                            {
                                Dictionary<string, object> keyValues1 = new Dictionary<string, object>()
                                {
                                    { nameof(RB_Goods_SpecificationPrice.SellingPrice),pupmodel.SellingPrice},
                                    { nameof(RB_Goods_SpecificationPrice.InventoryNum),pupmodel.InventoryNum},
                                    { nameof(RB_Goods_SpecificationPrice.GoodsWeight),pupmodel.GoodsWeight},
                                    { nameof(RB_Goods_SpecificationPrice.GoodsNumbers),pupmodel.GoodsNumbers},
                                    { nameof(RB_Goods_SpecificationPrice.Commission),pupmodel.Commission},
                                    { nameof(RB_Goods_SpecificationPrice.CostMoney),pupmodel.CostMoney},
                                };
                                List<WhereHelper> wheres1 = new List<WhereHelper>()
                                {
                                    new WhereHelper()
                                    {
                                            FiledName=nameof(RB_Goods_SpecificationPrice.Id),
                                            FiledValue=item.Id,
                                            OperatorEnum=OperatorEnum.Equal
                                    }
                                 };
                                flag = groupbuy_Activity_SpecificationPriceRepository.Update(keyValues1, wheres1);
                            }
                        }
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 新增修改阶梯团价
        /// </summary>
        /// <param name="extModel"></param>
        /// <param name="isChange"></param>
        /// <param name="oldSeparateDistributionType"></param>
        /// <returns></returns>
        private bool SetGoodGroupStepModule(RB_Groupbuy_Activity_Extend extModel, bool isChange,int oldSeparateDistributionType)
        {
            bool flag = true;
            var stepList = stepRepository.GetGroupBuyActivityListRepository(new RB_Groupbuy_Activity_Step_Extend() { GoodId = extModel.GoodId, MallBaseId = extModel.MallBaseId, TenantId = extModel.TenantId });
            if (isChange || (stepList.Count() != extModel.GroupList.Count() || stepList.Count() != extModel.GroupList.Where(qitem => qitem.StepId > 0).Count()))
            {
                stepRepository.Delete(new WhereHelper(nameof(RB_Groupbuy_Activity_Step_Extend.GoodId), extModel.GoodId));
                groupbuy_Activity_Step_PriceRepository.Delete(new WhereHelper(nameof(RB_Groupbuy_Activity_Step_Price_Extend.GoodId), extModel.GoodId));
                groupBuy_DistributioncommissionRepository.Delete(new WhereHelper(nameof(RB_GroupBuy_Distributioncommission_Extend.GoodsId), extModel.GoodId));
                groupbuy_MemberpriceRepository.Delete(new WhereHelper(nameof(RB_Groupbuy_Memberprice_Extend.GoodsId), extModel.GoodId));
                foreach (var groupItem in extModel.GroupList)
                {
                    var groupModel = new RB_Groupbuy_Activity_Step_Extend()
                    {
                        TenantId = extModel.TenantId,
                        MallBaseId = extModel.MallBaseId,
                        GoodId = extModel.GoodId,
                        People_Num = groupItem.People_Num,
                        Preferential_Price = groupItem.Preferential_Price,
                        Pintuan_Time = groupItem.Pintuan_Time,
                        Group_Num = groupItem.Group_Num,
                    };
                    var newStepId = stepRepository.Insert(groupModel);
                    groupModel.StepId = newStepId;
                    flag = newStepId > 0;

                    if (groupModel.StepId > 0)
                    {
                        if (groupItem.StepPriceList != null && groupItem.StepPriceList.Count > 0)
                        {
                            //添加会员价格
                            foreach (var subItem in groupItem.StepPriceList)
                            {
                                var stepPriceModel = new RB_Groupbuy_Activity_Step_Price_Extend()
                                {
                                    MallBaseId = extModel.MallBaseId,
                                    TenantId = extModel.TenantId,
                                    GoodId = extModel.GoodId,
                                    StepId = groupModel.StepId,
                                    PinTuanPrice = subItem.PinTuanPrice,
                                    PinTuanStock = subItem.PinTuanStock,
                                    SpecificationSort = subItem.SpecificationSort,
                                    SortNum = subItem.SortNum,
                                };
                                flag = groupbuy_Activity_Step_PriceRepository.Insert(stepPriceModel) > 0;
                            }
                        }
                        //设置分销佣金
                        SetDistributioncommissionModule(extModel, groupItem, groupModel.StepId, isCreate: true);

                        //会员价设置
                        if (groupItem.MemberpriceList != null && groupItem.MemberpriceList.Count > 0)
                        {
                            foreach (var subItem in groupItem.MemberpriceList)
                            {
                                if (subItem.GradeMemberPriceList != null && subItem.GradeMemberPriceList.Count > 0)
                                {
                                    foreach (var childItem in subItem.GradeMemberPriceList)
                                    {
                                        var memberModel = new RB_Groupbuy_Memberprice_Extend()
                                        {
                                            SpecificationSort = subItem.SpecificationSort,
                                            GoodsId = extModel.GoodId,
                                            Status = 0,
                                            TenantId = extModel.TenantId,
                                            MallBaseId = extModel.MallBaseId,
                                            StepId = groupModel.StepId,
                                            CreateDate = DateTime.Now,
                                            UpdateDate = DateTime.Now,
                                            MemberGrade = childItem.MemberGrade,
                                            MemberPrice = childItem.MemberPrice,
                                        };
                                        var newMemberId = groupbuy_MemberpriceRepository.Insert(memberModel);
                                        memberModel.Id = newMemberId;
                                        flag = newMemberId > 0;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                var stepPriceList = groupbuy_Activity_Step_PriceRepository.GetGroupbuyActivitySpecificationpriceListRepository(new RB_Groupbuy_Activity_Step_Price_Extend()
                {
                    GoodId = extModel.GoodId,
                    TenantId = extModel.TenantId,
                    MallBaseId = extModel.MallBaseId
                });
                var memberPriceList = groupbuy_MemberpriceRepository.GetGroupBuyMemberpriceRepository(new RB_Groupbuy_Memberprice_Extend()
                {
                    GoodsId = extModel.GoodId,
                    TenantId = extModel.TenantId,
                    MallBaseId = extModel.MallBaseId
                });
                foreach (var item in stepList)
                {
                    var stepModel = extModel.GroupList.Where(qitem => qitem.StepId == item.StepId).FirstOrDefault();
                    Dictionary<string, object> stepFileds = new Dictionary<string, object>()
                    {
                        { nameof(RB_Groupbuy_Activity_Step_Extend.People_Num),stepModel.People_Num},
                        { nameof(RB_Groupbuy_Activity_Step_Extend.Preferential_Price),stepModel.Preferential_Price},
                        { nameof(RB_Groupbuy_Activity_Step_Extend.Pintuan_Time),stepModel.Pintuan_Time},
                        { nameof(RB_Groupbuy_Activity_Step_Extend.Group_Num),stepModel.Group_Num},
                    };
                    flag= stepRepository.Update(stepFileds, new WhereHelper(nameof(RB_Groupbuy_Activity_Step_Extend.StepId), item.StepId));

                    //更新价格和库存
                    foreach (var subItem in stepModel.StepPriceList)
                    {
                        var subPriceModel = stepPriceList.Where(qitem => qitem.StepId == item.StepId&&qitem.SpecificationSort==subItem.SpecificationSort).FirstOrDefault();
                        Dictionary<string, object> stepPriceFileds = new Dictionary<string, object>()
                        {
                            { nameof(RB_Groupbuy_Activity_Step_Price_Extend.PinTuanPrice),subItem.PinTuanPrice},
                            { nameof(RB_Groupbuy_Activity_Step_Price_Extend.PinTuanStock),subItem.PinTuanStock},
                            { nameof(RB_Groupbuy_Activity_Step_Price_Extend.SortNum),subItem.SortNum},
                        };
                        flag = groupbuy_Activity_Step_PriceRepository.Update(stepPriceFileds, new WhereHelper(nameof(RB_Groupbuy_Activity_Step_Price_Extend),subItem.Id));
                    }

                    //更新会员价
                    foreach (var subItem in stepModel.MemberpriceList)
                    {
                        foreach (var childItem in subItem.GradeMemberPriceList)
                        {
                            var memberPriceModel = memberPriceList.Where(qitem => qitem.StepId == item.StepId && qitem.SpecificationSort == subItem.SpecificationSort).FirstOrDefault();
                            Dictionary<string, object> memberPriceFileds = new Dictionary<string, object>()
                            {
                                { nameof(RB_Groupbuy_Memberprice_Extend.MemberGrade),childItem.MemberGrade},
                                { nameof(RB_Groupbuy_Memberprice_Extend.MemberPrice),childItem.MemberPrice},
                            };
                            flag = groupbuy_MemberpriceRepository.Update(memberPriceFileds, new WhereHelper(nameof(RB_Groupbuy_Memberprice_Extend), childItem.Id));
                        }
                    }
                    if (oldSeparateDistributionType !=extModel.SeparateDistributionType)
                    {
                        groupbuy_MemberpriceRepository.Delete(new WhereHelper(nameof(RB_Groupbuy_Memberprice_Extend.GoodsId), extModel.GoodId));
                        //设置分销佣金
                        SetDistributioncommissionModule(extModel, stepModel, item.StepId, isCreate: true);
                    }
                    else
                    {
                        //设置分销佣金
                        SetDistributioncommissionModule(extModel, stepModel, item.StepId, isCreate: false);
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 添加修改分销佣金
        /// </summary>
        /// <param name="extModel"></param>
        /// <param name="groupItem"></param>
        /// <param name="StepId"></param>
        /// <returns></returns>
        private bool SetDistributioncommissionModule(RB_Groupbuy_Activity_Extend extModel, RB_Groupbuy_Activity_Step_Extend groupItem,int StepId,bool isCreate=true)
        {
            bool flag = false;
            //新增分销佣金
            if (isCreate)
            {
                //普通设置
                if (extModel.SeparateDistributionType == 1)
                {
                    //分销商分销佣金设置
                    if (groupItem.DistributioncommissionList != null && groupItem.DistributioncommissionList.Count > 0)
                    {
                        foreach (var subItem in groupItem.DistributioncommissionList)
                        {
                            var commissionModel = new RB_GroupBuy_Distributioncommission_Extend()
                            {
                                GoodsId = extModel.GoodId,
                                Status = 0,
                                TenantId = extModel.TenantId,
                                MallBaseId = extModel.MallBaseId,
                                StepId = StepId,
                                UpdateDate = DateTime.Now,
                                CreateDate = DateTime.Now,
                                SpecificationSort = subItem.SpecificationSort,
                                DistributorGrade = subItem.DistributorGrade,
                                OneCommission = subItem.OneCommission,
                                TwoCommission = subItem.TwoCommission,
                                ThreeCommission = subItem.ThreeCommission,
                            };
                            var newDistriId = groupBuy_DistributioncommissionRepository.Insert(commissionModel);
                            commissionModel.Id = newDistriId;
                            flag = newDistriId > 0;
                        }
                    }
                } //详细设置
                else if (extModel.SeparateDistributionType == 2)
                {
                    if (groupItem.DistributionCommissionTreeList != null && groupItem.DistributionCommissionTreeList.Count > 0)
                    {
                        foreach (var subItem in groupItem.DistributionCommissionTreeList)
                        {
                            if (subItem.GradeCommissionList != null && subItem.GradeCommissionList.Count > 0)
                            {
                                foreach (var childItem in subItem.GradeCommissionList)
                                {
                                    var commissionModel = new RB_GroupBuy_Distributioncommission_Extend()
                                    {
                                        GoodsId = extModel.GoodId,
                                        Status = 0,
                                        TenantId = extModel.TenantId,
                                        MallBaseId = extModel.MallBaseId,
                                        StepId = StepId,
                                        UpdateDate = DateTime.Now,
                                        CreateDate = DateTime.Now,
                                        SpecificationSort = subItem.SpecificationSort,
                                        DistributorGrade = childItem.DistributorGrade,
                                        OneCommission = childItem.OneCommission,
                                        TwoCommission = childItem.TwoCommission,
                                        ThreeCommission = childItem.ThreeCommission,
                                    };
                                    var newDistriId = groupBuy_DistributioncommissionRepository.Insert(commissionModel);
                                    commissionModel.Id = newDistriId;
                                    flag = newDistriId > 0;
                                }
                            }
                        }
                    }
                }
            }
            //修改分销佣金
            else
            {
                var distributionList = groupBuy_DistributioncommissionRepository.GetGroupBuyCommissionRepository(new RB_GroupBuy_Distributioncommission_Extend()
                {
                    GoodsId = extModel.GoodId,
                    TenantId = extModel.TenantId,
                    MallBaseId = extModel.MallBaseId
                });
                //普通设置
                if (extModel.SeparateDistributionType == 1)
                {
                    foreach (var item in distributionList)
                    {
                        var defaultModel = groupItem.DistributioncommissionList.Where(qitem => qitem.StepId == item.StepId && qitem.SpecificationSort == item.SpecificationSort && qitem.DistributorGrade == item.DistributorGrade).FirstOrDefault();
                        Dictionary<string, object> comFileds = new Dictionary<string, object>()
                        {
                            { nameof(RB_GroupBuy_Distributioncommission_Extend.OneCommission),defaultModel.OneCommission},
                            { nameof(RB_GroupBuy_Distributioncommission_Extend.TwoCommission),defaultModel.TwoCommission},
                            { nameof(RB_GroupBuy_Distributioncommission_Extend.ThreeCommission),defaultModel.ThreeCommission},
                        };
                        flag = groupBuy_DistributioncommissionRepository.Update(comFileds,new WhereHelper(nameof(RB_GroupBuy_Distributioncommission_Extend.Id), defaultModel.Id));
                    }
                } //详细设置
                else if (extModel.SeparateDistributionType == 2)
                {
                    if (groupItem.DistributionCommissionTreeList != null && groupItem.DistributionCommissionTreeList.Count > 0)
                    {
                        foreach (var subItem in groupItem.DistributionCommissionTreeList)
                        {
                            if (subItem.GradeCommissionList != null && subItem.GradeCommissionList.Count > 0)
                            {
                                foreach (var childItem in subItem.GradeCommissionList)
                                {
                                    var oldModel= distributionList.Where(qitem => qitem.StepId == childItem.StepId && qitem.SpecificationSort == subItem.SpecificationSort && qitem.DistributorGrade == childItem.DistributorGrade).FirstOrDefault();
                                    var defaultModel = groupItem.DistributioncommissionList.Where(qitem => qitem.StepId == childItem.StepId && qitem.SpecificationSort == subItem.SpecificationSort && qitem.DistributorGrade == childItem.DistributorGrade).FirstOrDefault();
                                    Dictionary<string, object> comFileds = new Dictionary<string, object>()
                                    {
                                        { nameof(RB_GroupBuy_Distributioncommission_Extend.OneCommission),defaultModel.OneCommission},
                                        { nameof(RB_GroupBuy_Distributioncommission_Extend.TwoCommission),defaultModel.TwoCommission},
                                        { nameof(RB_GroupBuy_Distributioncommission_Extend.ThreeCommission),defaultModel.ThreeCommission},
                                    };
                                    flag = groupBuy_DistributioncommissionRepository.Update(comFileds, new WhereHelper(nameof(RB_GroupBuy_Distributioncommission_Extend.Id), oldModel.Id));
                                }
                            }
                        }
                    }
                }
            }
            return flag;
        }


        /// <summary>
        /// 根据编号删除活动商品规格
        /// </summary>
        /// <returns></returns>
        public bool RemoveGroupBuySpecificationModule(object Id)
        {
            //根据商品规格删除商品价格
            //List<WhereHelper> specValues = new List<WhereHelper>()
            //{
            //  new WhereHelper(nameof(RB_Groupbuy_Activity_Specificationprice_Extend.SpecificationId),Id)
            //};
            //groupbuy_Activity_SpecificationPriceRepository.Delete(specValues);
            return groupbuy_Activity_SpecificationPriceRepository.Delete(Id) > 0;
        }

        /// <summary>
        /// 根据编号删除活动商品规格值
        /// </summary>
        /// <returns></returns>
        public bool RemoveGroupBuySpecificationValueModule(object Id)
        {
            //根据规格值删除价格
            //List<WhereHelper> specValues = new List<WhereHelper>()
            //{
            //  new WhereHelper(nameof(RB_Groupbuy_Activity_Specificationprice_Extend.SpecificationValueId),Id)
            //};
            //groupbuy_Activity_SpecificationPriceRepository.Delete(specValues);
            return groupbuy_Activity_SpecificationValueRepository.Delete(Id) > 0;
        }
    }
}
