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>
        /// <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.ActivityId));
                //List<RB_Groupbuy_Activity_Step_Extend> groupList = new List<RB_Groupbuy_Activity_Step_Extend>();
                //if (!string.IsNullOrEmpty(Ids))
                //{
                //    groupList = GetGroupBuyActivityListModule(new RB_Groupbuy_Activity_Step_Extend()
                //    {
                //        MallBaseId = query.MallBaseId,
                //        TenantId = query.TenantId,
                //        GoodIds = Ids
                //    });
                //}
                //foreach (var item in list)
                //{
                //    item.GroupList = groupList?.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)
                    {
                        List<object> AttrList = new List<object>();
                        var smodel = specificationList?.Where(qitem => qitem.Id == item.SpecificationId)?.FirstOrDefault() ?? new RB_Groupbuy_Activity_Specification_Extend();
                        var svmodel = specificationvalueList.Where(qitem => qitem.Id == item.SpecificationValueId)?.FirstOrDefault() ?? new RB_Groupbuy_Activity_Specificationvalue_Extend();
                        AttrList.Add(new
                        {
                            SName = smodel.Name,
                            SId = smodel.Id,
                            SVId = svmodel.Sort,
                            SVName = svmodel.Name
                        });
                        item.AttrList = AttrList;
                    }
                }

                //拼团阶梯基础设置列表
                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,
                });

                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>();
                    }
                }
                extModel.SpecificationList = specificationList;
                extModel.SpecificationPriceList = specPriceList;
                extModel.GroupList = groupStepList;
            }
            return extModel;
        }

        /// <summary>
        /// 新增修改拼团活动
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public virtual bool SetGroupbuyActivityModule(RB_Groupbuy_Activity_Extend extModel)
        {
            bool flag = false;
            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},
                };
                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);

                flag = SetGoodGroupStepModule(extModel);
            }
            return flag;
        }

        /// <summary>
        /// 添加修改商品规格
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        private bool SetGoodsSpecificationModule(RB_Groupbuy_Activity_Extend extModel)
        {
            bool flag = false;
            if (extModel.IsCustomSpecification == 1)
            {
                foreach (var specItem in extModel.SpecificationList)
                {
                    specItem.TenantId = extModel.TenantId;
                    specItem.MallBaseId = extModel.MallBaseId;
                    specItem.GoodsId = extModel.GoodId;
                    specItem.Status = 0;
                    specItem.CreateDate = DateTime.Now;
                    if (specItem.Id > 0)
                    {
                        flag= groupbuy_Activity_SpecificationRepository.Update(specItem);
                    }
                    else
                    {
                        var newSpecId = groupbuy_Activity_SpecificationRepository.Insert(specItem);
                        specItem.Id = newSpecId;
                        flag = newSpecId > 0;
                    }
                    if (specItem.SpecificationValueList != null && specItem.SpecificationValueList.Count > 0)
                    {
                        foreach (var specValueItem in specItem.SpecificationValueList)
                        {
                            specValueItem.MallBaseId = extModel.MallBaseId;
                            specValueItem.TenantId = extModel.TenantId;
                            specValueItem.SpecificationId = specItem.Id;
                            specValueItem.GoodsId = extModel.GoodId;
                            specValueItem.CreateDate = DateTime.Now;
                            specValueItem.Status = 0;
                            if (specValueItem.Id > 0)
                            {
                                flag= groupbuy_Activity_SpecificationValueRepository.Update(specValueItem);
                            }
                            else
                            {
                                var specValueId = groupbuy_Activity_SpecificationValueRepository.Insert(specValueItem);
                                specValueItem.Id = specValueId;
                                flag = specValueId > 0;
                            }
                        }
                    }
                }

                foreach (var priceItem in extModel.SpecificationPriceList)
                {
                    priceItem.MallBaseId = extModel.MallBaseId;
                    priceItem.TenantId = extModel.TenantId;
                    priceItem.GoodsId = extModel.GoodId;
                    priceItem.Status = 0;
                    priceItem.CreateDate = DateTime.Now;
                    priceItem.UpdateDate = DateTime.Now;
                    var specArray = priceItem.SpecificationSort.Split(":");
                    if (specArray != null && specArray.Length>0 )
                    {
                        int.TryParse(specArray[0], out int specIndex);
                        int specValueIndex = 1;
                        if (specArray.Length == 2)
                        {
                            int.TryParse(specArray[1], out specValueIndex);
                        }
                        priceItem.SpecificationId = extModel?.SpecificationList[specIndex-1]?.Id ?? 0;
                        priceItem.SpecificationValueId = extModel?.SpecificationList[specIndex-1]?.SpecificationValueList[specValueIndex-1]?.Id ?? 0;
                    }
                    if (priceItem.Id > 0)
                    {
                       flag= groupbuy_Activity_SpecificationPriceRepository.Update(priceItem);
                    }
                    else 
                    {
                        flag = groupbuy_Activity_SpecificationPriceRepository.Insert(priceItem)>0;
                    }
                }

            }
            return flag;
        }

        /// <summary>
        /// 新增修改阶梯团价
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        private bool SetGoodGroupStepModule(RB_Groupbuy_Activity_Extend extModel)
        {
            bool flag = false;
            if (extModel.GroupList != null && extModel.GroupList.Count > 0)
            {
                foreach (var groupItem in extModel.GroupList)
                {
                    groupItem.TenantId = extModel.TenantId;
                    groupItem.MallBaseId = extModel.MallBaseId;
                    groupItem.GoodId = extModel.GoodId;
                    if (groupItem.StepId > 0)
                    {
                        flag = stepRepository.Update(groupItem);
                    }
                    else
                    {
                        var newStepId = stepRepository.Insert(groupItem);
                        groupItem.StepId = newStepId;
                        flag = newStepId > 0;
                    }
                    if (groupItem.StepId > 0)
                    {
                        if (groupItem.StepPriceList != null && groupItem.StepPriceList.Count > 0)
                        {
                            //添加会员价格
                            foreach (var subItem in groupItem.StepPriceList)
                            {
                                subItem.MallBaseId = extModel.MallBaseId;
                                subItem.TenantId = extModel.TenantId;
                                subItem.GoodId = extModel.GoodId;
                                subItem.StepId = groupItem.StepId;
                                if (subItem.Id > 0)
                                {
                                    flag = groupbuy_Activity_Step_PriceRepository.Update(subItem);
                                }
                                else
                                {
                                    flag = groupbuy_Activity_Step_PriceRepository.Insert(subItem)>0;
                                }
                            }
                        }
                    }
                }
            }
            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;
        }
    }
}
