using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Mall.AOP.CustomerAttribute;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Entity.BaseSetUp;
using Mall.Model.Entity.GuideCar;
using Mall.Model.Entity.Product;
using Mall.Model.Entity.User;
using Mall.Model.Extend.BaseSetUp;
using Mall.Model.Extend.GuideCar;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.User;
using Mall.Model.Query;
using Mall.Repository.BaseSetUp;
using Mall.Repository.GuideCar;
using Mall.Repository.Product;
using Mall.Repository.User;
using Newtonsoft.Json;
using VT.FW.DB;

namespace Mall.Module.Product
{
    /// <summary>
    /// 司导专区处理层
    /// </summary>
    public class GuideCarModule
    {
        /// <summary>
        /// 素材分组
        /// </summary>
        private readonly RB_Material_GroupRepository material_GroupRepository = new RB_Material_GroupRepository();
        /// <summary>
        /// 素材管理
        /// </summary>
        private readonly RB_Material_InfoRepository material_InfoRepository = new RB_Material_InfoRepository();
        /// <summary>
        /// 商品分类
        /// </summary>
        private readonly RB_Product_CategoryRepository product_CategoryRepository = new RB_Product_CategoryRepository();
        /// <summary>
        /// 商品
        /// </summary>
        private readonly RB_GoodsRepository goodsRepository = new RB_GoodsRepository();
        /// <summary>
        /// 商品日志
        /// </summary>
        private readonly RB_Goods_LogRepository goods_LogRepository = new RB_Goods_LogRepository();
        /// <summary>
        /// 商品区域
        /// </summary>
        private readonly RB_Goods_AreaRepository goods_AreaRepository = new RB_Goods_AreaRepository();
        /// <summary>
        /// 商品分类
        /// </summary>
        private readonly RB_Goods_CategoryRepository goods_CategoryRepository = new RB_Goods_CategoryRepository();
        /// <summary>
        /// 分销商等级
        /// </summary>
        private readonly RB_Distributor_GradeRepository distributor_GradeRepository = new RB_Distributor_GradeRepository();
        /// <summary>
        /// 分销商
        /// </summary>
        private readonly RB_Distributor_InfoRepository distributor_InfoRepository = new RB_Distributor_InfoRepository();
        /// <summary>
        /// 分销基础配置
        /// </summary>
        private readonly RB_Distributor_BasicsRepository distributor_BasicsRepository = new RB_Distributor_BasicsRepository();
        /// <summary>
        /// 会员等级
        /// </summary>
        private readonly RB_Member_GradeRepository member_GradeRepository = new RB_Member_GradeRepository();
        /// <summary>
        /// 用户管理
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <summary>
        /// 商品分销佣金
        /// </summary>
        private readonly RB_Goods_DistributionCommissionRepository goods_DistributionCommissionRepository = new RB_Goods_DistributionCommissionRepository();
        /// <summary>
        /// 商品会员价格
        /// </summary>
        private readonly RB_Goods_MemberPriceRepository goods_MemberPriceRepository = new RB_Goods_MemberPriceRepository();
        /// <summary>
        /// 商户仓储层对象
        /// </summary>
        private Mall.Repository.User.RB_MiniProgramRepository programRepository = new Repository.User.RB_MiniProgramRepository();
        /// <summary>
        /// 商品收藏
        /// </summary>
        private readonly RB_Member_CollectionRepository member_CollectionRepository = new RB_Member_CollectionRepository();
        /// <summary>
        /// 收货地址
        /// </summary>
        private readonly RB_Member_ShippingAddressRepository member_ShippingAddressRepository = new RB_Member_ShippingAddressRepository();
        /// <summary>
        /// 订单商品
        /// </summary>
        private readonly RB_Goods_OrderRepository goods_OrderRepository = new RB_Goods_OrderRepository();
        /// <summary>
        /// 地区处理
        /// </summary>
        private readonly Rb_destinationRepository destinationRepository = new Rb_destinationRepository();
        /// <summary>
        /// 商品分销
        /// </summary>
        private readonly RB_MiniProgram_GoodPosterRepository miniProgram_GoodPosterRepository = new RB_MiniProgram_GoodPosterRepository();
        /// <summary>
        /// 粉象返佣
        /// </summary>
        private readonly RB_Distributor_FXGradeRepository distributor_FXGradeRepository = new RB_Distributor_FXGradeRepository();
        /// <summary>
        /// 粉象VIP返佣比例
        /// </summary>
        private readonly RB_Distributor_FXCommissionRepository distributor_FXCommissionRepository = new RB_Distributor_FXCommissionRepository();
        /// <summary>
        /// 微店基础
        /// </summary>
        private RB_SmallShops_CustomRepository smallShops_CustomRepository = new RB_SmallShops_CustomRepository();
        /// <summary>
        /// 微店
        /// </summary>
        private RB_SmallShops_InfoRepository smallShops_InfoRepository = new RB_SmallShops_InfoRepository();
        /// <summary>
        /// 微店商品价格
        /// </summary>
        private RB_SmallShops_PriceRepository smallShops_PriceRepository = new RB_SmallShops_PriceRepository();
        /// <summary>
        /// 司导站点
        /// </summary>
        private RB_GuideCar_SiteRepository SiteRepository = new RB_GuideCar_SiteRepository();
        /// <summary>
        /// 司导站点地区
        /// </summary>
        private RB_GuideCar_SiteRegionRepository SiteRegionRepository = new RB_GuideCar_SiteRegionRepository();
        /// <summary>
        /// 司导基础配置
        /// </summary>
        private RB_GuideCar_BaseRepository guideCar_BaseRepository = new RB_GuideCar_BaseRepository();


        #region 基础配置
        /// <summary>
        /// 获取基础配置
        /// </summary>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public RB_GuideCar_Base_Extend GetGuideCarInfo(int tenantId, int mallBaseId)
        {
            var model = guideCar_BaseRepository.GetList(new RB_GuideCar_Base_Extend() { TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            if (model == null) {
                model = new RB_GuideCar_Base_Extend() { 
                     AdvanceDay=1,
                      MallBaseId=mallBaseId,
                       CancelHour=1,
                        CostPrice=0,
                         Id=0,
                          InsuranceDescription="",
                           InsuranceName="",
                            IsConfirm=1,
                             PagePath="",
                              
                };
            }
            return model;
        }

        #endregion



        #region 站点配置
        /// <summary>
        /// 包邮规则列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_GuideCar_Site_Extend> GetGuideCarSiteList(int pageIndex, int pageSize, out long rowCount, RB_GuideCar_Site_Extend query)
        {
            List<RB_GuideCar_Site_Extend> list = SiteRepository.GetPageListRepository(pageIndex, pageSize, out rowCount, query);
            if (list != null && list.Any())
            {
                List<RB_GuideCar_SiteRegion_Extend> listLogisticsRulesRegion = SiteRegionRepository.GetListRepository(new RB_GuideCar_SiteRegion_Extend { TenantId = query.TenantId, RulesType =1, MallBaseId = query.MallBaseId, SiteIds = string.Join(",", list.Select(x => x.ID)) });
                foreach (var item in list)
                {
                    item.RegionList = new List<RB_GuideCar_SiteRegion_Extend>();
                    item.RegionList = listLogisticsRulesRegion.Where(x => x.SiteId == item.ID).ToList();
                }
            }
            return list;
        }

        /// <summary>
        /// 包邮实体
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public RB_GuideCar_Site_Extend GetGuideCarSiteModel(RB_GuideCar_Site_Extend query)
        {
            RB_GuideCar_Site_Extend model = SiteRepository.GetLogisticsRulesList(query).FirstOrDefault();
            if (model != null)
            {
                List<RB_GuideCar_SiteRegion_Extend> listLogisticsRulesRegion = SiteRegionRepository.GetListRepository(new RB_GuideCar_SiteRegion_Extend { TenantId = query.TenantId, RulesType = query.RulesType, MallBaseId = query.MallBaseId, SiteId = model.ID });
                model.RegionList = new List<RB_GuideCar_SiteRegion_Extend>();
                model.RegionList = listLogisticsRulesRegion;
            }

            return model;
        }

        /// <summary>
        /// 新增/修改基础信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrUpdateGuideCarSite(RB_GuideCar_Site_Extend model)
        {
            bool flag = false;
            var trans = SiteRepository.DbTransaction;
            try
            {
                int rulesId = 0;
                if (model.ID == 0)
                {
                    rulesId = SiteRepository.Insert(model, trans);
                    flag = rulesId > 0;
                }
                else
                {
                    rulesId = model.ID;
                    flag = SiteRepository.Update(model, trans);

                    List<RB_GuideCar_SiteRegion_Extend> listLogisticsRulesRegion = SiteRegionRepository.GetListRepository(new RB_GuideCar_SiteRegion_Extend { TenantId = model.TenantId, RulesType = model.RulesType, MallBaseId = model.MallBaseId, SiteId = model.ID });

                    //删除之前的区域
                    foreach (var itemRegion in listLogisticsRulesRegion.Where(x => x.SiteId == model.ID))
                    {
                        IDictionary<string, object> filedsRegion = new Dictionary<string, object>()//删除价格下面对应的地区
                                 {
                                    { nameof(RB_GuideCar_SiteRegion.Status),1},
                                    { nameof(RB_GuideCar_SiteRegion.UpdateDate),System.DateTime.Now},
                                  };
                        IList<WhereHelper> whereHelpersRegion = new List<WhereHelper>()
                                {
                                    new WhereHelper (){ FiledName=nameof(RB_GuideCar_SiteRegion.ID),FiledValue=itemRegion.ID,OperatorEnum=OperatorEnum.Equal}
                                };
                        SiteRegionRepository.Update(filedsRegion, whereHelpersRegion, trans);
                    }
                }
                if (model.RegionList != null && model.RegionList.Any())
                {
                    model.RegionList.ForEach(x => x.TenantId = model.TenantId);
                    model.RegionList.ForEach(x => x.CreateDate = System.DateTime.Now);
                    model.RegionList.ForEach(x => x.ID = 0);
                    model.RegionList.ForEach(x => x.SiteId = rulesId);
                    model.RegionList.ForEach(x => x.RulesType = model.RulesType);
                    model.RegionList.ForEach(x => x.MallBaseId = model.MallBaseId);
                    SiteRegionRepository.InsertBatch(model.RegionList, trans);
                }

                SiteRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "AddOrUpdateGuideCarSite");
                SiteRepository.DBSession.Rollback("AddOrUpdateGuideCarSite");
                return false;
            }
            return flag;
        }

        /// <summary>
        /// 删除包邮规则
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool DelGuideCarSiteInfo(int id, int uid, int mallBaseId)
        {
            var trans = SiteRepository.DbTransaction;
            bool flag;
            try
            {
                Dictionary<string, object> cols = new Dictionary<string, object>()
                {
                    { nameof(RB_GuideCar_Site.Status),1},
                    { nameof(RB_GuideCar_Site.UpdateDate),DateTime.Now},
                };
                List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_GuideCar_Site.ID),
                        FiledValue=id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_GuideCar_Site.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_GuideCar_Site.MallBaseId),
                        FiledValue=Convert.ToInt32(mallBaseId),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_GuideCar_Site.RulesType),
                        FiledValue=Convert.ToInt32(Common.Enum.MallBase.RulesTypeEnum.Pinkage),
                        OperatorEnum=OperatorEnum.Equal
                }
            };
                flag = SiteRepository.Update(cols, wheres1, trans);

                IDictionary<string, object> filedsRegion = new Dictionary<string, object>()//删除价格下面对应的地区
                                 {
                                    { nameof(RB_GuideCar_SiteRegion.Status),1},
                                    { nameof(RB_GuideCar_SiteRegion.UpdateDate),System.DateTime.Now},
                                  };
                IList<WhereHelper> whereHelpersRegion = new List<WhereHelper>()
                                {
                                    new WhereHelper (){ FiledName=nameof(RB_GuideCar_SiteRegion.SiteId),FiledValue=id,OperatorEnum=OperatorEnum.Equal},
                new WhereHelper(){
                        FiledName=nameof(RB_GuideCar_SiteRegion.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_GuideCar_SiteRegion.MallBaseId),
                        FiledValue=Convert.ToInt32(mallBaseId),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_GuideCar_SiteRegion.RulesType),
                        FiledValue=Convert.ToInt32(Common.Enum.MallBase.RulesTypeEnum.Pinkage),
                        OperatorEnum=OperatorEnum.Equal
                }  };
                flag = SiteRegionRepository.Update(filedsRegion, whereHelpersRegion, trans);
                SiteRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "DelGuideCarSiteInfo");
                SiteRepository.DBSession.Rollback("DelGuideCarSiteInfo");
                return false;
            }
            return flag;
        }
        #endregion
    }
}
