using System;
using System.Collections.Generic;
using System.Text;
using Mall.Model.Extend.User;
using Mall.Repository;
using System.Linq;
using Mall.Model.Entity.User;
using Mall.CacheManager.AppletWeChat;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Mall.Common.Plugin;
using NPOI.SS.Formula.Functions;
using Mall.Repository.User;
using Mall.Model.Extend.Statistics;
using Mall.Model.Query;
using VT.FW.DB;
using Mall.Model.Extend.AppletWeChat;
using Mall.Model.Entity.AppletWeChat;
using Mall.Repository.AppletWeChat;

namespace Mall.Module.User
{
    /// <summary>
    /// 小程序处理类
    /// </summary>
    public class MiniProgramModule
    {
        /// <summary>
        /// 商户仓储层对象
        /// </summary>
        private readonly RB_MiniProgramRepository programRepository = new Repository.User.RB_MiniProgramRepository();

        /// <summary>
        /// 底部导航仓储层对象
        /// </summary>
        private readonly RB_Miniprogram_BottomnavRepository bottomnavRepository = new Repository.User.RB_Miniprogram_BottomnavRepository();

        /// <summary>
        /// 用户中心仓储层对象
        /// </summary>
        private readonly RB_MiniProgram_UserCenterMenuRepository centerMenuRepository = new Repository.User.RB_MiniProgram_UserCenterMenuRepository();

        /// <summary>
        /// 会员订阅消息仓储层对象
        /// </summary>
        private readonly RB_Member_SubscriptionRepository subscriptionRepository = new Repository.User.RB_Member_SubscriptionRepository();
        /// <summary>
        /// 会员仓储层对象
        /// </summary>
        private readonly RB_Member_UserRepository userRepository = new Repository.User.RB_Member_UserRepository();
        /// <summary>
        /// 直播房间仓储层对象
        /// </summary>
        private readonly RB_Live_HouseRepository liveHouseRepository = new Repository.AppletWeChat.RB_Live_HouseRepository();

        /// <summary>
        /// 直播房间仓储层对象
        /// </summary>
        private readonly RB_Live_HouseImgRepository liveHouseImgRepository = new Repository.AppletWeChat.RB_Live_HouseImgRepository();


        /// <summary>
        /// 轮播图表仓储层对象
        /// </summary>
        private readonly RB_Mall_NavRepository navRepository = new RB_Mall_NavRepository();

        /// <summary>
        /// 图片魔方表仓储层对象
        /// </summary>
        private readonly RB_Mall_MagicRepository magicRepository = new RB_Mall_MagicRepository();

        /// <summary>
        /// 用户共用模块
        /// </summary>
        private readonly UserCommonModule userCommonModule = new UserCommonModule();

        /// <summary>
        /// 首页统计
        /// </summary>
        private readonly MallStatisticsRepository mallStatisticsRepository = new MallStatisticsRepository();

        /// <summary>
        /// 直播配置仓储层
        /// </summary>
        private readonly RB_Live_ConfigRepository live_ConfigRepository = new RB_Live_ConfigRepository();


        #region 轮播图管理
        /// <summary>
        /// 轮播图分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Mall_Nav_Extend> GetMallNavPageListModule(int pageIndex, int pageSize, out long rowCount, RB_Mall_Nav_Extend query)
        {
            return navRepository.GetMallNavPageListRepository(pageIndex, pageSize, out rowCount, query);
        }

        /// <summary>
        /// 获取轮播图列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Mall_Nav_Extend> GetMallNavListModule(RB_Mall_Nav_Extend query)
        {
            return navRepository.GetMallNavListRepository(query);
        }

        /// <summary>
        /// 添加修改轮播图
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMallNavModule(RB_Mall_Nav_Extend extModel)
        {
            bool flag;
            if (extModel.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Mall_Nav_Extend.NavName),extModel.NavName.Trim()},
                    { nameof(RB_Mall_Nav_Extend.NavLink),extModel.NavLink},
                    { nameof(RB_Mall_Nav_Extend.NavImg),extModel.NavImg},
                };
                flag = navRepository.Update(fileds, new WhereHelper(nameof(RB_Mall_Nav_Extend.Id), extModel.Id));
            }
            else
            {
                int NewId = navRepository.Insert(extModel);
                extModel.Id = NewId;
                flag = NewId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 获取轮播图实体
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public RB_Mall_Nav_Extend GetMallNavModule(object Id)
        {
            var extModel = navRepository.GetEntity<RB_Mall_Nav_Extend>(Id);
            if (extModel == null)
            {
                extModel = new RB_Mall_Nav_Extend();
            }
            return extModel;
        }

        /// <summary>
        /// 删除轮播图
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveMallNavModule(object Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Mall_Nav_Extend.Status),1},
            };
            bool flag = navRepository.Update(fileds, new WhereHelper(nameof(RB_Mall_Nav_Extend.Id), Id));
            return flag;
        }

        #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_Mall_Magic_Extend> GetMallMagicPageListModule(int pageIndex, int pageSize, out long rowCount, RB_Mall_Magic_Extend query)
        {
            return magicRepository.GetMallMagicPageListRepository(pageIndex, pageSize, out rowCount, query);
        }

        /// <summary>
        /// 获取图片魔方列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Mall_Magic_Extend> GetMallMagicListModule(RB_Mall_Magic_Extend query)
        {
            var list = magicRepository.GetMallMagicListRepository(query);
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    if (item.MagicData != null && !string.IsNullOrEmpty(item.MagicData))
                    {
                        item.MagicDataList = Common.Plugin.JsonHelper.DeserializeObject<List<MagicItem>>(item.MagicData);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 添加修改图片魔方
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMallMagicModule(RB_Mall_Magic_Extend extModel)
        {
            bool flag;
            if (extModel.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Mall_Magic_Extend.Name),extModel.Name.Trim()},
                    { nameof(RB_Mall_Magic_Extend.Style),extModel.Style},
                    { nameof(RB_Mall_Magic_Extend.MagicData),extModel.MagicData},
                };
                flag = magicRepository.Update(fileds, new WhereHelper(nameof(RB_Mall_Magic_Extend.Id), extModel.Id));
            }
            else
            {
                int NewId = magicRepository.Insert(extModel);
                extModel.Id = NewId;
                flag = NewId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 获取图片魔方实体
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public RB_Mall_Magic_Extend GetMallMagicModule(object Id)
        {
            var extModel = magicRepository.GetEntity<RB_Mall_Magic_Extend>(Id);
            if (extModel == null)
            {
                extModel = new RB_Mall_Magic_Extend();
            }
            if (extModel.MagicData != null && !string.IsNullOrEmpty(extModel.MagicData))
            {
                extModel.MagicDataList = Common.Plugin.JsonHelper.DeserializeObject<List<MagicItem>>(extModel.MagicData);
            }
            return extModel;
        }

        /// <summary>
        /// 删除图片魔方
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveMallMagicModule(object Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_Mall_Magic_Extend.Status),1},
            };
            bool flag = magicRepository.Update(fileds, new WhereHelper(nameof(RB_Mall_Magic_Extend.Id), Id));
            return flag;
        }
        #endregion

        #region 小程序

        /// <summary>
        /// 根据查询条件获取小程序列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_MiniProgram_Extend> GetTenantListModule(RB_MiniProgram_Extend query)
        {
            return programRepository.GetListRepository(query);
        }

        /// <summary>
        /// 获取小程序分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_MiniProgram_Extend> GetMiniProgramPageListModule(int pageIndex, int pageSize, out long rowCount, RB_MiniProgram_Extend query)
        {
            return programRepository.GetPageListRepository(pageIndex, pageSize, out rowCount, query);
        }



        /// <summary>
        /// 判断用户是否存在
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool CheckMiniProgramModule(RB_MiniProgram_Extend extModel)
        {
            List<WhereHelper> wheres = new List<WhereHelper>()
            {
                new WhereHelper(nameof(RB_MiniProgram_Extend.MallName),extModel.MallName.Trim())
            };
            return programRepository.Exists(wheres);
        }

        /// <summary>
        /// 检查小程序数量
        /// </summary>
        /// <param name="TenantId">商户Id</param>
        /// <returns></returns>
        public int CheckMallNumModule(int TenantId)
        {
            return programRepository.CheckMallNumRepository(TenantId);
        }

        /// <summary>
        /// 添加修改小程序
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiniProgramModule(RB_MiniProgram_Extend extModel)
        {
            if (extModel.IsEffective == 1)
            {
                extModel.MallValidate = null;
            }
            bool flag;
            if (extModel.MallBaseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_MiniProgram_Extend.MallName),extModel.MallName.Trim()},
                    { nameof(RB_MiniProgram_Extend.IsEffective),extModel.IsEffective},
                    { nameof(RB_MiniProgram_Extend.MallValidate),extModel.MallValidate},
                };
                flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
            }
            else
            {
                extModel.MallName = extModel.MallName.Trim();
                extModel.CreateDate = DateTime.Now;
                int NewId = programRepository.Insert(extModel);
                extModel.MallBaseId = NewId;
                if (extModel.BottomTagList != null)
                {
                    SetMiniProgramMallTagModule(extModel, isUpdateBasic: false);
                }
                flag = NewId > 0;
                if (flag)
                {
                    userCommonModule.InitializeCategoryStyleInfo(extModel.TenantId ?? 0, NewId);//分类样式
                    userCommonModule.InitializeDistributorBasicsInfo(extModel.TenantId ?? 0, NewId);//分销基础
                    userCommonModule.InitializeDistributorCustomInfo(extModel.TenantId ?? 0, NewId);//分销自定义
                    userCommonModule.InitializeProductRecommendInfo(extModel.TenantId ?? 0, NewId);//商品推荐
                }
            }
            return flag;
        }

        /// <summary>
        /// 设置顶部和底部导航配置
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiniProgramMallTagModule(RB_MiniProgram_Extend extModel, bool isUpdateBasic = true)
        {
            bool flag = false;
            if (extModel.MallBaseId > 0)
            {
                if (isUpdateBasic)
                {
                    Dictionary<string, object> fileds = new Dictionary<string, object>()
                    {
                        { nameof(RB_MiniProgram_Extend.TopNavWordType),extModel.TopNavWordType},
                        { nameof(RB_MiniProgram_Extend.TopNavWordColor),extModel.TopNavWordColor},
                        { nameof(RB_MiniProgram_Extend.TopNavBgColor),extModel.TopNavBgColor},
                        { nameof(RB_MiniProgram_Extend.BottomNavBgColor),extModel.BottomNavBgColor},
                        { nameof(RB_MiniProgram_Extend.BottomNavIsShadow),extModel.BottomNavIsShadow},
                          { nameof(RB_MiniProgram_Extend.IsShowIcon),extModel.IsShowIcon},
                        
                    };
                    flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
                }

                if (extModel.BottomTagList != null && extModel.BottomTagList.Count > 0)
                {
                    int tagSort = 1;
                    foreach (var item in extModel.BottomTagList)
                    {
                        item.TagSort = tagSort;
                        if (item.TagId > 0)
                        {
                            Dictionary<string, object> tagfileds = new Dictionary<string, object>()
                            {
                                { nameof(RB_Miniprogram_Bottomnav_Extend.DefaultIcon),item.DefaultIcon},
                                { nameof(RB_Miniprogram_Bottomnav_Extend.CheckedIcon),item.CheckedIcon},
                                { nameof(RB_Miniprogram_Bottomnav_Extend.TagName),item.TagName},
                                { nameof(RB_Miniprogram_Bottomnav_Extend.DefaultColor),item.DefaultColor},
                                { nameof(RB_Miniprogram_Bottomnav_Extend.CheckedColor),item.CheckedColor},
                                { nameof(RB_Miniprogram_Bottomnav_Extend.TagLink),item.TagLink},
                                { nameof(RB_Miniprogram_Bottomnav_Extend.TagSort),item.TagSort},
                                { nameof(RB_Miniprogram_Bottomnav_Extend.TagType),item.TagType},
                            };
                            flag = bottomnavRepository.Update(tagfileds, new WhereHelper(nameof(RB_Miniprogram_Bottomnav_Extend.TagId), item.TagId));
                        }
                        else
                        {
                            item.MallBaseId = extModel.MallBaseId;
                            item.TenantId = extModel.TenantId;
                            item.Status = 0;
                            flag = bottomnavRepository.Insert(item) > 0;
                        }
                        tagSort++;
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 修改小程序版权信息
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiniProgramCopyRightModule(RB_MiniProgram_Extend extModel)
        {
            bool flag = false;
            if (extModel.MallBaseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_MiniProgram_Extend.CopyRightWord),extModel.CopyRightWord.Trim()},
                    { nameof(RB_MiniProgram_Extend.CopyRightImg),extModel.CopyRightImg},
                    { nameof(RB_MiniProgram_Extend.CopyRightLink),extModel.CopyRightLink},
                };
                if (extModel.IsOpenCopyRight >= 0)
                {
                    fileds.Add(nameof(RB_MiniProgram_Extend.IsOpenCopyRight), extModel.IsOpenCopyRight);
                }
                flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
            }
            return flag;
        }



        /// <summary>
        /// 根据编号获取小程序信息
        /// </summary>
        /// <param name="MallBaseId">小程序Id</param>
        /// <param name="isGetNav">是否获取顶部底部配置+底部标签导航(0-不获取,1-获取)</param>
        /// <param name="isGetUserCenterMenu">是否获取用户中心菜单</param>
        /// <param name="isGetHomeData">是否获取首页配置数据</param>
        /// <returns></returns>
        public RB_MiniProgram_Extend GetMiniProgramModule(RB_MiniProgram_Extend query, int isGetNav = 0, bool isGetUserCenterMenu = false, bool isGetHomeData = false)
        {
            RB_MiniProgram_Extend extModel = programRepository.GetMiniProgramRepository(query);
            if (extModel == null)
            {
                extModel = new RB_MiniProgram_Extend();
            }
            if (isGetNav == 1)
            {
                extModel.BottomTagList = GetMiniprogramBottomnavListModule(new RB_Miniprogram_Bottomnav_Extend() { MallBaseId = extModel.MallBaseId });
                if (extModel.BottomTagList != null && extModel.BottomTagList.Count > 0)
                {
                    extModel.BottomTagList.FirstOrDefault().IsActive = true;
                }
            }
            if (isGetUserCenterMenu)
            {
                var menuList = GetMiniProgramUserCenterMenuListModule(new RB_MiniProgram_UserCenterMenu_Extend() { MallBaseId = extModel.MallBaseId });
                if (menuList != null && menuList.Count > 0)
                {
                    extModel.FavoriteFootMenuList = menuList?.Where(qitem => qitem.MenuType == 1)?.ToList();
                    extModel.OrderMenuList = menuList?.Where(qitem => qitem.MenuType == 3)?.ToList();
                    extModel.SDOrderMenuList = menuList?.Where(qitem => qitem.MenuType == 7)?.ToList();
                    extModel.AccountMenuList = menuList?.Where(qitem => qitem.MenuType == 2)?.ToList();
                    extModel.SelfMenuList = menuList?.Where(qitem => qitem.MenuType == 4).OrderBy(qitem => qitem.PageSort)?.ToList();
                }

                if (!string.IsNullOrEmpty(extModel.MenuNavJson) && extModel.MenuNavJson != "[]")
                {
                    extModel.NavMoreList = JsonConvert.DeserializeObject<List<MenuNavMoreModel>>(extModel.MenuNavJson);
                }
                else
                {
                    extModel.NavMoreList = new List<MenuNavMoreModel>()
                    {
                        new MenuNavMoreModel()
                        {
                             Sort=1,
                             MenuNavTitle="",
                             MenuNavStyle=0,
                             TitleStyle=1,
                             MeunList=new List<RB_MiniProgram_UserCenterMenu>()
                        }
                    };
                }
            }
            if (isGetHomeData)
            {
                if (extModel.MallHomeData != null && !string.IsNullOrEmpty(extModel.MallHomeData))
                {
                    extModel.HomeDataList = Common.Plugin.JsonHelper.DeserializeObject<List<HomeItem>>(extModel.MallHomeData);
                }
            }
            if (extModel.AuthData != null && !string.IsNullOrEmpty(extModel.AuthData))
            {
                extModel.AuthDataList = Common.Plugin.JsonHelper.DeserializeObject<List<AuthItem>>(extModel.AuthData);
            }
            return extModel;
        }

        /// <summary>
        /// 根据查询条件获取小程序用户中心菜单列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_MiniProgram_UserCenterMenu_Extend> GetMiniProgramUserCenterMenuListModule(RB_MiniProgram_UserCenterMenu_Extend query)
        {
            return centerMenuRepository.GetMiniProgramUserCenterMenuListRepository(query);
        }

        /// <summary>
        /// 删除小程序用户中心菜单
        /// </summary>
        /// <param name="DetailIds">详情编号</param>
        /// <param name="MallBaseId">商城编号</param>
        /// <returns></returns>
        public bool DeleteMiniProgramUserCenterMenuModule(string DetailIds = "", int MallBaseId = 0)
        {
            return centerMenuRepository.DeleteMiniProgramUserCenterMenuRepository(DetailIds: DetailIds, MallBaseId: MallBaseId);
        }

        /// <summary>
        /// 更新小程序状态
        /// </summary>
        /// <param name="MallBaseId">小程序Id</param>
        /// <param name="Status">小程序状态</param>
        /// <returns></returns>
        public bool SetMiniProgramModule(object MallBaseId, int Status)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_MiniProgram_Extend.Status),Status},
            };
            bool flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), MallBaseId));
            return flag;
        }

        /// <summary>
        /// 更新小程序状态
        /// </summary>
        /// <param name="MallBaseId">小程序Id</param>
        /// <param name="Status">小程序状态</param>
        /// <returns></returns>
        public bool SetMiniProgramStatusModule(object MallBaseId, int Status)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_MiniProgram_Extend.Status),Status},
            };
            bool flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), MallBaseId));
            return flag;
        }

        /// <summary>
        /// 更新小程序回收状态
        /// </summary>
        /// <param name="MallBaseId">小程序Id</param>
        /// <param name="Is_Recycle">小程序回收状态</param>
        /// <returns></returns>
        public bool SetMiniProgramRecycleModule(object MallBaseId, int Is_Recycle)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                { nameof(RB_MiniProgram_Extend.Is_Recycle),Is_Recycle},
            };
            bool flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), MallBaseId));
            return flag;
        }

        /// <summary>
        /// 修改小程序商城风格信息
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiniProgramMallShopStyleModule(RB_MiniProgram_Extend extModel)
        {
            bool flag = false;
            if (extModel.MallBaseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_MiniProgram_Extend.MallShopStyle),extModel.MallShopStyle},
                };
                flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
            }
            return flag;
        }
        /// <summary>
        /// 更新相亲拼拼plus风格
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiaiPPPlusStyle(RB_MiniProgram_Extend extModel)
        {
            bool flag = false;
            if (extModel.MallBaseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_MiniProgram_Extend.MiaiPPPlusStyle),extModel.MiaiPPPlusStyle},
                };
                flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
            }
            return flag;
        }

        /// <summary>
        /// 修改小程序首页布局
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiniProgramMallHomeModule(RB_MiniProgram_Extend extModel)
        {
            bool flag = false;
            if (extModel.MallBaseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_MiniProgram_Extend.MallHomeData),extModel.MallHomeData},
                };
                flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
            }
            return flag;
        }

        /// <summary>
        /// 修改小程序首页布局
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiniProgramMallAuthModule(RB_MiniProgram_Extend extModel)
        {
            bool flag = false;
            if (extModel.MallBaseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_MiniProgram_Extend.IsOpenAuth),extModel.IsOpenAuth},
                    { nameof(RB_MiniProgram_Extend.AuthUrl),extModel.AuthUrl},
                    { nameof(RB_MiniProgram_Extend.AuthData),extModel.AuthData},
                };
                flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
            }
            return flag;
        }

        /// <summary>
        /// 根据查询条件获取小程序底部导航标签列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Miniprogram_Bottomnav_Extend> GetMiniprogramBottomnavListModule(RB_Miniprogram_Bottomnav_Extend query)
        {
            return bottomnavRepository.GetMiniprogramBottomnavListRepository(query);
        }

        /// <summary>
        /// 删除小程序底部导航
        /// </summary>
        /// <param name="TagId"></param>
        /// <returns></returns>
        public bool RemoveMiniProgramMallTagModule(string TagId)
        {
            bool flag = bottomnavRepository.DeleteBottomnavRepository(TagId);
            return flag;
        }

        /// <summary>
        /// 修改微信小程序配置信息
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiniProgramAppConfigModule(RB_MiniProgram_Extend extModel)
        {
            bool flag = false;
            if (extModel.MallBaseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_MiniProgram_Extend.MiniAppId),extModel.MiniAppId},
                    { nameof(RB_MiniProgram_Extend.MiniAppSecret),extModel.MiniAppSecret},
                    { nameof(RB_MiniProgram_Extend.WeChatPayMerchants),extModel.WeChatPayMerchants},
                    { nameof(RB_MiniProgram_Extend.WeChatApiSecret),extModel.WeChatApiSecret},
                    { nameof(RB_MiniProgram_Extend.WeChatPayCertificate),extModel.WeChatPayCertificate},
                    { nameof(RB_MiniProgram_Extend.WeChatPayPrivateKey),extModel.WeChatPayPrivateKey},
                    { nameof(RB_MiniProgram_Extend.WeChatPayCertificateUrl),extModel.WeChatPayCertificateUrl},
                };
                flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
            }
            return flag;
        }

        /// <summary>
        /// 修改微信小程序商城订阅配置信息
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiniProgramMallSubscribeModule(RB_MiniProgram_Extend extModel)
        {
            bool flag = false;
            if (extModel.MallBaseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_MiniProgram_Extend.OrderSuccessTpl),extModel.OrderSuccessTpl},
                    { nameof(RB_MiniProgram_Extend.OrderCancelTpl),extModel.OrderCancelTpl},
                    { nameof(RB_MiniProgram_Extend.OrderDeliverGoodsTpl),extModel.OrderDeliverGoodsTpl},
                    { nameof(RB_MiniProgram_Extend.RefundTpl),extModel.RefundTpl},
                    { nameof(RB_MiniProgram_Extend.ActiveStateTpl),extModel.ActiveStateTpl},
                    { nameof(RB_MiniProgram_Extend.AuditResultTpl),extModel.AuditResultTpl},
                };
                flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
            }
            return flag;
        }





        /// <summary>
        /// 修改微信小程序商城订阅配置信息
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetAllMiniProgramMallSubscribeModule(RB_MiniProgram_Extend extModel)
        {
            bool flag = false;
            if (extModel.MallBaseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_MiniProgram_Extend.OrderSuccessTpl),extModel.OrderSuccessTpl},
                    { nameof(RB_MiniProgram_Extend.OrderCancelTpl),extModel.OrderCancelTpl},
                    { nameof(RB_MiniProgram_Extend.OrderDeliverGoodsTpl),extModel.OrderDeliverGoodsTpl},
                    { nameof(RB_MiniProgram_Extend.RefundTpl),extModel.RefundTpl},
                    { nameof(RB_MiniProgram_Extend.ActiveStateTpl),extModel.ActiveStateTpl},
                    { nameof(RB_MiniProgram_Extend.AuditResultTpl),extModel.AuditResultTpl},
                     { nameof(RB_MiniProgram_Extend.ReflectSuccessTpl),extModel.ReflectSuccessTpl},
                    { nameof(RB_MiniProgram_Extend.ReflectFailTpl),extModel.ReflectFailTpl},
                    { nameof(RB_MiniProgram_Extend.MembersLevelChangeTpl),extModel.MembersLevelChangeTpl},
                };
                flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
            }
            return flag;
        }
        /// <summary>
        /// 修改微信小程序分销订阅配置信息
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiniProgramMallDistributionModule(RB_MiniProgram_Extend extModel)
        {
            bool flag = false;
            if (extModel.MallBaseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_MiniProgram_Extend.ReflectSuccessTpl),extModel.ReflectSuccessTpl},
                    { nameof(RB_MiniProgram_Extend.ReflectFailTpl),extModel.ReflectFailTpl},
                    { nameof(RB_MiniProgram_Extend.MembersLevelChangeTpl),extModel.MembersLevelChangeTpl},
                };
                flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
            }
            return flag;
        }

        /// <summary>
        /// 小程序用户中心配置
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiniUserCenterConfigModule(RB_MiniProgram_Extend extModel)
        {
            bool flag = false;
            if (extModel.MallBaseId > 0)
            {
                #region 组装菜单栏
                if (extModel.NavMoreList != null && extModel.NavMoreList.Any())
                {
                    extModel.MenuNavJson = JsonConvert.SerializeObject(extModel.NavMoreList.Select(x => new
                    {
                        x.Sort,
                        x.MenuNavTitle,
                        x.TitleStyle,
                        x.MenuNavStyle,
                        MeunList = x.MeunList.Select(z => new
                        {
                            z.PageSort,
                            z.MenuName,
                            z.MenuIcon,
                            z.MenuUrl
                        })
                    }));
                }
                else
                {
                    extModel.MenuNavJson = "[]";
                }
                #endregion
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_MiniProgram_Extend.DefaultBgImg),extModel.DefaultBgImg},
                    { nameof(RB_MiniProgram_Extend.MemberBgImg),extModel.MemberBgImg},
                    { nameof(RB_MiniProgram_Extend.VipBgImg),extModel.VipBgImg},
                    { nameof(RB_MiniProgram_Extend.MemberBuyVipImg),extModel.MemberBuyVipImg},
                    { nameof(RB_MiniProgram_Extend.HeadStyle),extModel.HeadStyle},
                    { nameof(RB_MiniProgram_Extend.HeadStyleStr),extModel.HeadStyleStr},
                    { nameof(RB_MiniProgram_Extend.IsShowFavorite),extModel.IsShowFavorite},
                    { nameof(RB_MiniProgram_Extend.IsShowOrderNav),extModel.IsShowOrderNav},
                    { nameof(RB_MiniProgram_Extend.IsShowSDNav),extModel.IsShowSDNav},
                    { nameof(RB_MiniProgram_Extend.IsShowAccountNav),extModel.IsShowAccountNav},
                    { nameof(RB_MiniProgram_Extend.IsShowMenuNav),extModel.IsShowMenuNav},
                    { nameof(RB_MiniProgram_Extend.MenuNavTitle),extModel.MenuNavTitle},
                    { nameof(RB_MiniProgram_Extend.MenuNavStyle),extModel.MenuNavStyle},
                    { nameof(RB_MiniProgram_Extend.MenuNavJson),extModel.MenuNavJson},
                };
                if (extModel.FavoriteFootMenuList != null && extModel.FavoriteFootMenuList.Count > 0)
                {
                    foreach (var item in extModel.FavoriteFootMenuList)
                    {
                        item.MallBaseId = extModel.MallBaseId;
                        if (item.DetailId > 0)
                        {
                            Dictionary<string, object> detailesFileds = new Dictionary<string, object>()
                            {
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuType),item.MenuType},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuName),item.MenuName},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuIcon),item.MenuIcon},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuUrl),item.MenuUrl},
                            };
                            flag = centerMenuRepository.Update(detailesFileds, new WhereHelper(nameof(RB_MiniProgram_UserCenterMenu_Extend.DetailId), item.DetailId));
                        }
                        else
                        {
                            flag = centerMenuRepository.Insert(item) > 0;
                        }
                    }
                }
                if (extModel.OrderMenuList != null && extModel.OrderMenuList.Count > 0)
                {
                    foreach (var item in extModel.OrderMenuList)
                    {
                        item.MallBaseId = extModel.MallBaseId;
                        if (item.DetailId > 0)
                        {
                            Dictionary<string, object> detailesFileds = new Dictionary<string, object>()
                            {
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuType),item.MenuType},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuName),item.MenuName},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuIcon),item.MenuIcon},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuUrl),item.MenuUrl},
                            };
                            flag = centerMenuRepository.Update(detailesFileds, new WhereHelper(nameof(RB_MiniProgram_UserCenterMenu_Extend.DetailId), item.DetailId));
                        }
                        else
                        {
                            flag = centerMenuRepository.Insert(item) > 0;
                        }
                    }
                }
                if (extModel.SDOrderMenuList != null && extModel.SDOrderMenuList.Count > 0)
                {
                    foreach (var item in extModel.SDOrderMenuList)
                    {
                        item.MallBaseId = extModel.MallBaseId;
                        if (item.DetailId > 0)
                        {
                            Dictionary<string, object> detailesFileds = new Dictionary<string, object>()
                            {
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuType),item.MenuType},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuName),item.MenuName},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuIcon),item.MenuIcon},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuUrl),item.MenuUrl},
                            };
                            flag = centerMenuRepository.Update(detailesFileds, new WhereHelper(nameof(RB_MiniProgram_UserCenterMenu_Extend.DetailId), item.DetailId));
                        }
                        else
                        {
                            flag = centerMenuRepository.Insert(item) > 0;
                        }
                    }
                }
                if (extModel.AccountMenuList != null && extModel.AccountMenuList.Count > 0)
                {
                    foreach (var item in extModel.AccountMenuList)
                    {
                        item.MallBaseId = extModel.MallBaseId;
                        if (item.DetailId > 0)
                        {
                            Dictionary<string, object> detailesFileds = new Dictionary<string, object>()
                            {
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuType),item.MenuType},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuName),item.MenuName},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuIcon),item.MenuIcon},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuUrl),item.MenuUrl},
                            };
                            flag = centerMenuRepository.Update(detailesFileds, new WhereHelper(nameof(RB_MiniProgram_UserCenterMenu_Extend.DetailId), item.DetailId));
                        }
                        else
                        {
                            flag = centerMenuRepository.Insert(item) > 0;
                        }
                    }
                }
                if (extModel.SelfMenuList != null && extModel.SelfMenuList.Count > 0)
                {
                    int pageSort = 1;
                    foreach (var item in extModel.SelfMenuList)
                    {
                        item.PageSort = pageSort;
                        item.MallBaseId = extModel.MallBaseId;
                        if (item.DetailId > 0)
                        {
                            Dictionary<string, object> detailesFileds = new Dictionary<string, object>()
                            {
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuType),item.MenuType},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuName),item.MenuName},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuIcon),item.MenuIcon},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.MenuUrl),item.MenuUrl},
                                { nameof(RB_MiniProgram_UserCenterMenu_Extend.PageSort),item.PageSort},
                            };
                            flag = centerMenuRepository.Update(detailesFileds, new WhereHelper(nameof(RB_MiniProgram_UserCenterMenu_Extend.DetailId), item.DetailId));
                        }
                        else
                        {
                            flag = centerMenuRepository.Insert(item) > 0;
                        }
                        pageSort++;
                    }
                }
                flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
            }
            return flag;
        }


        /// <summary>
        /// 删除小程序用户中心自定义菜单
        /// </summary>
        /// <param name="DetailId"></param>
        /// <returns></returns>
        public bool RemoveMiniUserCenterMenuModule(object DetailId)
        {
            bool flag = centerMenuRepository.Delete(DetailId) > 0;
            return flag;
        }

        /// <summary>
        /// 修改相亲小程序活动样式
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiniProgramActivityStyleModule(RB_MiniProgram_Extend extModel)
        {
            bool flag = false;
            if (extModel.MallBaseId > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_MiniProgram_Extend.ActivityStyle),extModel.ActivityStyle},
                };
                flag = programRepository.Update(fileds, new WhereHelper(nameof(RB_MiniProgram_Extend.MallBaseId), extModel.MallBaseId));
            }
            return flag;
        }


        #endregion

        #region 微信小程序基础配置


        /// <summary>
        /// 修改微信小程序可跳转程序
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateJumpAppId(RB_MiniProgram_Extend model)
        {
            IDictionary<string, object> fileds = new Dictionary<string, object>()
                         {
                            { nameof(RB_MiniProgram_Extend.JumpAppId),model.JumpAppId},
                          };
            IList<WhereHelper> whereHelpers = new List<WhereHelper>()
                        {
                            new WhereHelper (){ FiledName=nameof(RB_MiniProgram.MallBaseId),FiledValue=model.MallBaseId,OperatorEnum=OperatorEnum.Equal}
                        };
            return programRepository.Update(fileds, whereHelpers);
        }




        /// <summary>
        /// 修改微信小程序是否开启直播
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateLivePlayerPlugin(RB_MiniProgram_Extend model)
        {
            IDictionary<string, object> fileds = new Dictionary<string, object>()
                         {
                            { nameof(RB_MiniProgram_Extend.LivePlayerPlugin),model.LivePlayerPlugin},
                          };
            IList<WhereHelper> whereHelpers = new List<WhereHelper>()
                        {
                            new WhereHelper (){ FiledName=nameof(RB_MiniProgram.MallBaseId),FiledValue=model.MallBaseId,OperatorEnum=OperatorEnum.Equal}
                        };
            return programRepository.Update(fileds, whereHelpers);
        }


        /// <summary>
        /// 修改当前小程序发布的版本号
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateVersion(RB_MiniProgram_Extend model)
        {
            IDictionary<string, object> fileds = new Dictionary<string, object>()
                         {
                            { nameof(RB_MiniProgram_Extend.Version),model.Version},
                          };
            IList<WhereHelper> whereHelpers = new List<WhereHelper>()
                        {
                            new WhereHelper (){ FiledName=nameof(RB_MiniProgram.MallBaseId),FiledValue=model.MallBaseId,OperatorEnum=OperatorEnum.Equal}
                        };
            return programRepository.Update(fileds, whereHelpers);
        }


        #endregion

        #region 发送小程序订阅信息




        /// <summary>
        /// 用户订阅消息
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetMemberSubscribe(RB_Member_Subscription_Extend demodel)
        {
            var gmodel = userRepository.GetEntity(demodel.UserId);
            if (gmodel == null)
            {
                return false;
            }

            var trans = subscriptionRepository.DbTransaction;
            try
            {
                foreach (var item in demodel.TempleteIdList)
                {
                    var list = subscriptionRepository.GetList(new RB_Member_Subscription_Extend() { OpenId = demodel.OpenId, Type = 1, TempleteId = item, MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId });
                    if (!list.Any())
                    {
                        subscriptionRepository.Insert(new RB_Member_Subscription()
                        {
                            UserId = demodel.UserId,
                            Id = 0,
                            OpenId = demodel.OpenId,
                            Status = 0,
                            TempleteId = item,
                            Type = 1,
                            Count = 1,
                            MallBaseId = gmodel.MallBaseId,
                            TenantId = gmodel.TenantId
                        }, trans);
                    }
                    else
                    {
                        // 增加订阅次数
                        var model = list.FirstOrDefault();
                        Dictionary<string, object> files = new Dictionary<string, object>() {
                            { nameof(RB_Member_Subscription.Count),model.Count++}
                        };
                        List<WhereHelper> wheres = new List<WhereHelper>() {
                            new WhereHelper(){
                                 FiledName=nameof(RB_Member_Subscription.Id),
                                  FiledValue=model.Id,
                                   OperatorEnum=OperatorEnum.Equal
                            }
                        };
                        subscriptionRepository.Update(files, wheres, trans);
                    }
                }
                subscriptionRepository.DBSession.Commit();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetLXYGuestSubscribe");
                subscriptionRepository.DBSession.Rollback();
                return false;
            }
        }


        /// <summary>
        /// 获取订阅模板数量
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public List<RB_Member_Subscription_Extend> GetLXYSubscribeCountList(string openId, int MallBaseId, int TenantId)
        {
            return subscriptionRepository.GetList(new RB_Member_Subscription_Extend() { OpenId = openId, Type = 1, MallBaseId = MallBaseId, TenantId = TenantId });
        }

        /// <summary>
        /// 下单取消发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="OrderNo">订单编号</param>
        /// <param name="CancelReason">取消原因</param>
        /// <param name="OrderMoney">订单金额</param>
        /// <param name="GoodsName">商品</param>
        /// <returns></returns>
        public bool SendOrderCancelMsg(int TenantId, int MallBaseId, string OpenId, string OrderNo, string CancelReason, string OrderMoney, string GoodsName)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.OrderCancelTpl,
                    page = "pages/order/index/index",
                    data = new
                    {
                        character_string1 = new
                        {
                            value = OrderNo
                        },
                        thing7 = new
                        {
                            value = CancelReason
                        },
                        amount4 = new
                        {
                            value = "￥" + OrderMoney
                        },
                        name8 = new
                        {
                            value = GoodsName
                        }
                    }
                };

                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");

                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {//成功
                    //var list = subscriptionRepository.GetList(new RB_Member_Subscription_Extend() { OpenId = OpenId, Type = 1, TempleteId = appletWeChatModel.OrderCancelTpl, MallBaseId = MallBaseId, TenantId = TenantId });
                    //if (list.Any())
                    //{
                    //    // 减少订阅次数
                    //    var model = list.FirstOrDefault();
                    //    Dictionary<string, object> files = new Dictionary<string, object>() {
                    //        { nameof(RB_Member_Subscription.Count),model.Count>0?( model.Count--):0 }
                    //    };
                    //    List<WhereHelper> wheres = new List<WhereHelper>() {
                    //        new WhereHelper(){
                    //             FiledName=nameof(RB_Member_Subscription.Id),
                    //              FiledValue=model.Id,
                    //               OperatorEnum=OperatorEnum.Equal
                    //        }
                    //    };
                    //    subscriptionRepository.Update(files, wheres);
                    //}
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendOrderCancelMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }



        /// <summary>
        /// 发货通知发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Remark">备注</param>
        /// <param name="TrackingNumber">快递单号</param>
        /// <param name="Company">快递公司</param>
        /// <param name="GoodsName">商品名称</param>
        /// <returns></returns>
        public bool SendOrderDeliverMsg(int TenantId, int MallBaseId, string OpenId, string Remark, string TrackingNumber, string Company, string GoodsName)
        {

            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.OrderDeliverGoodsTpl,
                    page = "pages/order/index/index",
                    data = new
                    {
                        thing8 = new
                        {
                            value = Remark
                        },
                        character_string4 = new
                        {
                            value = TrackingNumber
                        },
                        thing7 = new
                        {
                            value = Company
                        },
                        thing2 = new
                        {
                            value = GoodsName
                        }
                    }
                };

                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");

                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {//成功
                    //var list = subscriptionRepository.GetList(new RB_Member_Subscription_Extend() { OpenId = OpenId, Type = 1, TempleteId = appletWeChatModel.OrderDeliverGoodsTpl, MallBaseId = MallBaseId, TenantId = TenantId });
                    //if (list.Any())
                    //{
                    //    // 减少订阅次数
                    //    var model = list.FirstOrDefault();
                    //    Dictionary<string, object> files = new Dictionary<string, object>() {
                    //        { nameof(RB_Member_Subscription.Count),model.Count>0?( model.Count--):0 }
                    //    };
                    //    List<WhereHelper> wheres = new List<WhereHelper>() {
                    //        new WhereHelper(){
                    //             FiledName=nameof(RB_Member_Subscription.Id),
                    //              FiledValue=model.Id,
                    //               OperatorEnum=OperatorEnum.Equal
                    //        }
                    //    };
                    //    subscriptionRepository.Update(files, wheres);
                    //}
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendOrderDeliverMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }


        /// <summary>
        /// 退款通知发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Remark">退款原因</param>
        /// <param name="OrderNo">订单号</param>
        /// <param name="OrderMoney">退款金额</param>
        /// <param name="GoodsName">商品名称</param>
        /// <returns></returns>
        public bool SendOrderRefundMsg(int TenantId, int MallBaseId, string OpenId, string Remark, string OrderNo, string OrderMoney, string GoodsName)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.RefundTpl,
                    page = "pages/order/index/index",
                    data = new
                    {
                        character_string4 = new
                        {
                            value = OrderNo
                        },
                        thing5 = new
                        {
                            value = GoodsName
                        },
                        amount2 = new
                        {
                            value = OrderMoney + "元"
                        },
                        thing1 = new
                        {
                            value = Remark
                        }
                    }
                };

                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");

                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {//成功
                    //var list = subscriptionRepository.GetList(new RB_Member_Subscription_Extend() { OpenId = OpenId, Type = 1, TempleteId = appletWeChatModel.RefundTpl, MallBaseId = MallBaseId, TenantId = TenantId });
                    //if (list.Any())
                    //{
                    //    // 减少订阅次数
                    //    var model = list.FirstOrDefault();
                    //    Dictionary<string, object> files = new Dictionary<string, object>() {
                    //        { nameof(RB_Member_Subscription.Count),model.Count>0?( model.Count--):0 }
                    //    };
                    //    List<WhereHelper> wheres = new List<WhereHelper>() {
                    //        new WhereHelper(){
                    //             FiledName=nameof(RB_Member_Subscription.Id),
                    //              FiledValue=model.Id,
                    //               OperatorEnum=OperatorEnum.Equal
                    //        }
                    //    };
                    //    subscriptionRepository.Update(files, wheres);
                    //}
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendOrderRefundMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }


        /// <summary>
        /// 活动状态发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="ActivityName">活动名称</param>
        /// <param name="Progress">活动进度</param>
        /// <param name="Remark">温馨提示</param>
        /// <returns></returns>
        public bool SendActivityStateMsg(int TenantId, int MallBaseId, string OpenId, string ActivityName, string Progress, string Remark)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.ActiveStateTpl,
                    page = Mall.Common.Config.FirstPage,
                    data = new
                    {
                        thing1 = new
                        {
                            value = ActivityName
                        },
                        thing2 = new
                        {
                            value = Progress
                        },
                        thing4 = new
                        {
                            value = Remark
                        }
                    }
                };

                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");

                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {//成功
                    //var list = subscriptionRepository.GetList(new RB_Member_Subscription_Extend() { OpenId = OpenId, Type = 1, TempleteId = appletWeChatModel.ActiveStateTpl, MallBaseId = MallBaseId, TenantId = TenantId });
                    //if (list.Any())
                    //{
                    //    // 减少订阅次数
                    //    var model = list.FirstOrDefault();
                    //    Dictionary<string, object> files = new Dictionary<string, object>() {
                    //        { nameof(RB_Member_Subscription.Count),model.Count>0?( model.Count--):0 }
                    //    };
                    //    List<WhereHelper> wheres = new List<WhereHelper>() {
                    //        new WhereHelper(){
                    //             FiledName=nameof(RB_Member_Subscription.Id),
                    //              FiledValue=model.Id,
                    //               OperatorEnum=OperatorEnum.Equal
                    //        }
                    //    };
                    //    subscriptionRepository.Update(files, wheres);
                    //}
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendActivityStateMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }

        /// <summary>
        /// 审核结果通知发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Remark">审核说明</param>
        /// <param name="Result">审核结果</param>
        /// <param name="UserName">审核对象</param>
        /// <param name="CreateDate">审核时间</param>
        /// <returns></returns>
        public bool SendAuditResultMsg(int TenantId, int MallBaseId, string OpenId, string Remark, string Result, string UserName, string CreateDate)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.AuditResultTpl,
                    page = Mall.Common.Config.FirstPage,
                    data = new
                    {
                        thing4 = new
                        {
                            value = Remark
                        },
                        phrase2 = new
                        {
                            value = Result
                        },
                        thing1 = new
                        {
                            value = UserName
                        },
                        time3 = new
                        {
                            value = CreateDate
                        }
                    }
                };
                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");

                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {//成功
                    //var list = subscriptionRepository.GetList(new RB_Member_Subscription_Extend() { OpenId = OpenId, Type = 1, TempleteId = appletWeChatModel.AuditResultTpl, MallBaseId = MallBaseId, TenantId = TenantId });
                    //if (list.Any())
                    //{
                    //    // 减少订阅次数
                    //    var model = list.FirstOrDefault();
                    //    Dictionary<string, object> files = new Dictionary<string, object>() {
                    //        { nameof(RB_Member_Subscription.Count),model.Count>0?( model.Count--):0 }
                    //    };
                    //    List<WhereHelper> wheres = new List<WhereHelper>() {
                    //        new WhereHelper(){
                    //             FiledName=nameof(RB_Member_Subscription.Id),
                    //              FiledValue=model.Id,
                    //               OperatorEnum=OperatorEnum.Equal
                    //        }
                    //    };
                    //    subscriptionRepository.Update(files, wheres);
                    //}
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendAuditResultMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }


        /// <summary>
        /// 提现成功通知发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Monry">提现金额</param>
        /// <param name="ServiceCharge">手续费</param>
        /// <param name="Type">打款方式</param>
        /// <param name="Remark">打款原因</param>
        /// <returns></returns>
        public bool SendWithdrawSucceedMsg(int TenantId, int MallBaseId, string OpenId, string Monry, string ServiceCharge, string Type, string Remark)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.ReflectSuccessTpl,
                    page = Mall.Common.Config.FirstPage,
                    data = new
                    {
                        amount1 = new
                        {
                            value = "￥" + Monry
                        },
                        amount2 = new
                        {
                            value = "￥" + ServiceCharge
                        },
                        thing3 = new
                        {
                            value = Type
                        },
                        thing4 = new
                        {
                            value = Remark
                        }
                    }
                };
                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");

                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {//成功
                    //var list = subscriptionRepository.GetList(new RB_Member_Subscription_Extend() { OpenId = OpenId, Type = 1, TempleteId = appletWeChatModel.ReflectSuccessTpl, MallBaseId = MallBaseId, TenantId = TenantId });
                    //if (list.Any())
                    //{
                    //    // 减少订阅次数
                    //    var model = list.FirstOrDefault();
                    //    Dictionary<string, object> files = new Dictionary<string, object>() {
                    //        { nameof(RB_Member_Subscription.Count),model.Count>0?( model.Count--):0 }
                    //    };
                    //    List<WhereHelper> wheres = new List<WhereHelper>() {
                    //        new WhereHelper(){
                    //             FiledName=nameof(RB_Member_Subscription.Id),
                    //              FiledValue=model.Id,
                    //               OperatorEnum=OperatorEnum.Equal
                    //        }
                    //    };
                    //    subscriptionRepository.Update(files, wheres);
                    //}
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendWithdrawSucceedMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }


        /// <summary>
        /// 提现失败通知发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Monry">提现金额</param>
        /// <param name="Remark">备注</param>
        /// <returns></returns>
        public bool SendWithdrawFailMsg(int TenantId, int MallBaseId, string OpenId, string Monry, string Remark)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.ReflectFailTpl,
                    page = Mall.Common.Config.FirstPage,
                    data = new
                    {
                        amount1 = new
                        {
                            value = Monry
                        },
                        name2 = new
                        {
                            value = Remark
                        }
                    }
                };
                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");

                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {//成功
                    //var list = subscriptionRepository.GetList(new RB_Member_Subscription_Extend() { OpenId = OpenId, Type = 1, MallBaseId = MallBaseId, TempleteId = appletWeChatModel.ReflectFailTpl, TenantId = TenantId });
                    //if (list.Any())
                    //{
                    //    // 减少订阅次数
                    //    var model = list.FirstOrDefault();
                    //    Dictionary<string, object> files = new Dictionary<string, object>() {
                    //        { nameof(RB_Member_Subscription.Count),model.Count>0?( model.Count--):0 }
                    //    };
                    //    List<WhereHelper> wheres = new List<WhereHelper>() {
                    //        new WhereHelper(){
                    //             FiledName=nameof(RB_Member_Subscription.Id),
                    //              FiledValue=model.Id,
                    //               OperatorEnum=OperatorEnum.Equal
                    //        }
                    //    };
                    //    subscriptionRepository.Update(files, wheres);
                    //}
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SetLXYSubscribeSend:SendWithdrawFailMsg:{0}", wenXinResult));
                }
            }
            return false;
        }


        /// <summary>
        /// 提现失败通知发送订阅消息
        /// </summary>
        /// <param name="TenantId"></param>
        /// <param name="MallBaseId"></param>
        /// <param name="OpenId"></param>
        /// <param name="Remark">备注说明</param>
        /// <param name="CreateDate">变更时间</param>
        /// <returns></returns>
        public bool SendMemberLevelMsg(int TenantId, int MallBaseId, string OpenId, string Remark, string CreateDate)
        {
            var appletWeChatModel = programRepository.GetListRepository(new RB_MiniProgram_Extend { TenantId = TenantId, MallBaseId = MallBaseId }).FirstOrDefault();

            string token = WeiXinReidsCache.Get(appletWeChatModel.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, appletWeChatModel.MiniAppId, appletWeChatModel.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(appletWeChatModel.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token;
                var postdata = new
                {
                    touser = OpenId,
                    template_id = appletWeChatModel.MembersLevelChangeTpl,
                    page = Mall.Common.Config.FirstPage,
                    data = new
                    {
                        thing3 = new
                        {
                            value = Remark
                        },
                        date2 = new
                        {
                            value = CreateDate
                        }
                    }
                };
                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");

                JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (errcode == 0)
                {//成功
                    //var list = subscriptionRepository.GetList(new RB_Member_Subscription_Extend() { OpenId = OpenId, Type = 1, TempleteId = appletWeChatModel.MembersLevelChangeTpl, MallBaseId = MallBaseId, TenantId = TenantId });
                    //if (list.Any())
                    //{
                    //    // 减少订阅次数
                    //    var model = list.FirstOrDefault();
                    //    Dictionary<string, object> files = new Dictionary<string, object>() {
                    //        { nameof(RB_Member_Subscription.Count),model.Count>0?( model.Count--):0 }
                    //    };
                    //    List<WhereHelper> wheres = new List<WhereHelper>() {
                    //        new WhereHelper(){
                    //             FiledName=nameof(RB_Member_Subscription.Id),
                    //              FiledValue=model.Id,
                    //               OperatorEnum=OperatorEnum.Equal
                    //        }
                    //    };
                    //    subscriptionRepository.Update(files, wheres);
                    //}
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("SendMemberLevelMsg:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }

        /// <summary>
        /// 检查是否返回图片路径
        /// </summary>
        /// <param name="picStr"></param>
        /// <param name="TCID"></param>
        /// <param name="ConfigId"></param>
        /// <returns></returns>
        public string CheckWeiXinShareImg(string picStr, RB_MiniProgram_Extend model, string jumpUrl)
        {
            if (string.IsNullOrWhiteSpace(picStr))
            {

                string token = WeiXinReidsCache.Get(model.MiniAppId);
                if (string.IsNullOrEmpty(token))
                {
                    token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, model.MiniAppId, model.MiniAppSecret);
                    System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(model.MiniAppId, token));
                }
                if (string.IsNullOrEmpty(token))
                {
                    return "";
                }
                picStr = GetWeiXinShare(model, jumpUrl);
            }
            return picStr;
        }

        /// <summary>
        /// 获取微信小程序分享
        /// </summary>
        /// <returns></returns>
        public string GetWeiXinShare(RB_MiniProgram_Extend model, string jumpUrl)
        {
            string access_TokenStr = WeiXinReidsCache.Get(model.MiniAppId);
            if (string.IsNullOrEmpty(access_TokenStr))
            {
                access_TokenStr = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(access_TokenStr, model.MiniAppId, model.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(model.MiniAppId, access_TokenStr));
            }
            string picStr = string.Empty;
            if (!string.IsNullOrWhiteSpace(access_TokenStr))
            {
                string GetImageUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_TokenStr;
                var postData = new
                {
                    scene = "",
                    page = jumpUrl,
                    width = "100",
                    is_hyaline = true
                };
                picStr = HttpHelper.HttpPost(GetImageUrl, JsonHelper.Serialize(postData));
                //if (string.IsNullOrWhiteSpace(picStr))
                //{

                //    picStr = CheckWeiXinShareImg(picStr, model, jumpUrl);

                //}
            }
            return picStr;
        }



        #endregion

        #region 小程序直播房间信息




        /// <summary>
        /// 获取直播房间信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool GetLiveInfo(RB_MiniProgram_Extend model)
        {
            string token = WeiXinReidsCache.Get(model.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, model.MiniAppId, model.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(model.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return false;
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = " https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=" + token;
                var postdata = new
                {
                    start = 0,
                    limit = 100
                };
                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");

                var newLiveHouse = JsonConvert.DeserializeObject<Model.Extend.AppletWeChat.RB_Live_House_Extend>(wenXinResult);
                //JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                //int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (newLiveHouse.errcode == "0")
                {
                    newLiveHouse.room_info.ForEach(x => x.TenantId = model.TenantId ?? 0);
                    newLiveHouse.room_info.ForEach(x => x.MallBaseId = model.MallBaseId);
                    newLiveHouse.room_info.ForEach(x => x.CreateDate = System.DateTime.Now);

                    AddLiveHouse(newLiveHouse.room_info, new Model.Entity.AppletWeChat.RB_Live_House { TenantId = model.TenantId ?? 0, MallBaseId = model.MallBaseId });
                    return true;
                }
                else
                {
                    LogHelper.Write(string.Format("GetLiveInfo:wenXinResult:{0}", wenXinResult));
                }
            }
            return false;
        }


        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp">Unix时间戳格式</param>
        /// <returns>C#格式时间</returns>
        public static string GetTime(string timeStamp)
        {
            try
            {
                var start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                var longTimeSpan = long.Parse(timeStamp + "0000000");
                return start.AddMilliseconds(longTimeSpan).AddHours(8).ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception)
            {
                return "";
            }
        }



        public Model.Extend.AppletWeChat.PlayBack GetLiveReplayInfo(RB_MiniProgram_Extend model, int room_id)
        {
            string token = WeiXinReidsCache.Get(model.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, model.MiniAppId, model.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => WeiXinReidsCache.Set(model.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return new Model.Extend.AppletWeChat.PlayBack();
            }
            string wenXinResult = string.Empty;
            if (!string.IsNullOrWhiteSpace(token))
            {
                string Url = " http://api.weixin.qq.com/wxa/business/getliveinfo?access_token=" + token;
                var postdata = new
                {
                    action = "get_replay",
                    room_id,
                    start = 0,
                    limit = 100
                };
                wenXinResult = HttpHelper.HttpPost(Url, JsonHelper.Serialize(postdata), "");

                var newLiveHouse = JsonConvert.DeserializeObject<Model.Extend.AppletWeChat.PlayBack>(wenXinResult);
                //JObject jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);
                //int errcode = Convert.ToInt32(jo["errcode"].ToString());
                if (newLiveHouse.errcode == "0")
                {

                    return newLiveHouse;
                }
                else
                {
                    LogHelper.Write(string.Format("GetLiveInfo:wenXinResult:{0}", wenXinResult));
                }
            }
            return new Model.Extend.AppletWeChat.PlayBack();
        }


        /// <summary>
        /// 获取直播房间
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Live_HouseExtension_Extend> GetLiveHouseExtensionPageList(int pageIndex, int pageSize, out long rowCount, RB_Live_HouseExtension_Extend query)
        {
            return liveHouseRepository.GetLiveHouseExtensionPageList(pageIndex, pageSize, out rowCount, query);
        }
        public List<RB_Live_HouseExtension_Extend> GetLiveHousePageList(RB_Live_HouseExtension_Extend query)
        {
            return liveHouseRepository.GetLiveHousePageList(query);
        }



        /// <summary>
        /// 获取直播房间信息
        /// </summary>
        /// <param name="list"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public bool AddLiveHouse(List<Model.Entity.AppletWeChat.RB_Live_House> list, Model.Entity.AppletWeChat.RB_Live_House query)
        {
            try
            {
                var oldList = liveHouseRepository.GetLiveHouseListRepository(query);//获取之前的
                if (oldList != null && oldList.Any())
                {
                    liveHouseRepository.DeleteBatch(oldList);
                }

                if (list != null && list.Any())
                {
                    foreach (var item in list)
                    {
                        try
                        {
                            string datetime = GetTime(item.start_time);
                            if (!string.IsNullOrWhiteSpace(datetime))
                            {
                                item.LiveTime = Convert.ToDateTime(datetime);
                            }
                        }
                        catch (Exception)
                        {


                        }
                    }
                    liveHouseRepository.InsertBatch(list);
                }
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "AddLiveHouse");
                return false;
            }
        }

        /// <summary>
        /// 设置直播海报二维码样式
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetLiveQrCodeModule(RB_Live_HouseExtension_Extend extModel)
        {
            bool flag = false;
            if (extModel.ID > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Live_HouseExtension_Extend.LiveQrCodeSize),extModel.LiveQrCodeSize },
                    {nameof(RB_Live_HouseExtension_Extend.LiveQrCodePaddingLeft),extModel.LiveQrCodePaddingLeft },
                    {nameof(RB_Live_HouseExtension_Extend.LiveQrCodePaddingTop),extModel.LiveQrCodePaddingTop },
                    {nameof(RB_Live_HouseExtension_Extend.LiveQrCodeType),extModel.LiveQrCodeType },
                };
                flag = liveHouseRepository.Update(fileds, new WhereHelper(nameof(RB_Live_HouseExtension_Extend.ID), extModel.ID));
            }
            return flag;
        }

        /// <summary>
        /// 新增/修改基础信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrUpdateHouseImg(RB_Live_HouseImg model)
        {
            if (model.ID == 0)
            {
                return liveHouseImgRepository.Insert(model) > 0;
            }
            else
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Live_HouseImg.ExtensionImg),model.ExtensionImg},
                };

                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Live_HouseImg.ID),
                          FiledValue=model.ID,
                           OperatorEnum=OperatorEnum.Equal
                    },  new WhereHelper(){
                         FiledName=nameof(RB_Live_HouseImg.TenantId),
                          FiledValue=model.TenantId,
                           OperatorEnum=OperatorEnum.Equal
                    },  new WhereHelper(){
                         FiledName=nameof(RB_Live_HouseImg.MallBaseId),
                          FiledValue=model.MallBaseId,
                           OperatorEnum=OperatorEnum.Equal
                    }
                 };
                return liveHouseImgRepository.Update(keyValues, wheres);
            }
        }


        /// <summary>
        /// 删除物流规则
        /// </summary>
        /// <param name="gradeId"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool DelLiveHouseImg(int id, int uid, int mallBaseId)
        {
            Dictionary<string, object> cols = new Dictionary<string, object>()
                {
                    { nameof(RB_Live_HouseImg.Status),1},
                };
            List<WhereHelper> wheres1 = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName=nameof(RB_Live_HouseImg.ID),
                        FiledValue=id,
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Live_HouseImg.TenantId),
                        FiledValue=Convert.ToInt32(uid),
                        OperatorEnum=OperatorEnum.Equal
                },
                new WhereHelper(){
                        FiledName=nameof(RB_Live_HouseImg.MallBaseId),
                        FiledValue=Convert.ToInt32(mallBaseId),
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = liveHouseImgRepository.Update(cols, wheres1);
            return flag;
        }


        #endregion

        #region 首页统计

        /// <summary>
        /// 获取商城的总订单和总用户
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public MallIndexStatistics GetMallUserAndOrderModule(StatisticsQuery query)
        {
            return mallStatisticsRepository.GetMallUserAndOrderRepository(query);
        }

        /// <summary>
        /// 订单数量、商品、用户统计
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public MallIndexStatistics MallIndexStatisticsModule(StatisticsQuery query)
        {
            return mallStatisticsRepository.MallIndexStatisticsRepository(query);
        }

        /// <summary>
        /// 销售情况统计
        /// </summary>
        /// <param name="query"></param>
        public object MallIndexSalesStatisticsModule(StatisticsQuery query)
        {
            var list = mallStatisticsRepository.MallIndexSalesStatisticsRepository(query);
            List<object> resultList = new List<object>();
            List<MallSalesStatistics> subList = new List<MallSalesStatistics>();
            if (query.SalesTimeType == 1 || query.SalesTimeType == 0)
            {
                for (var i = 0; i <= 23; i++)
                {
                    var tempSubList = list?.Where(qitem => Convert.ToInt32(qitem.TimeStr) == i)?.ToList();
                    subList.Add(new MallSalesStatistics()
                    {
                        TimeStr = i.ToString(),
                        GoodCount = tempSubList?.Sum(qitem => qitem.GoodCount) ?? 0,
                        Income = tempSubList?.Sum(qitem => qitem.Income) ?? 0,
                        OrderCount = tempSubList?.Sum(qitem => qitem.OrderCount) ?? 0,
                        UserCount = tempSubList?.GroupBy(qitem => new { qitem.UserId }).Count() ?? 0,
                    });
                }
            }
            else
            {
                var startDate = DateTime.Now.AddDays(-7);
                for (var i = 0; i <= 7; i++)
                {
                    var tempSubList = list?.Where(qitem => qitem.TimeStr == startDate.AddDays(i).ToString("yyyy-MM-dd"))?.ToList();
                    subList.Add(new MallSalesStatistics()
                    {
                        TimeStr = startDate.AddDays(i).ToString("yyyy-MM-dd"),
                        GoodCount = tempSubList?.Sum(qitem => qitem.GoodCount) ?? 0,
                        Income = tempSubList?.Sum(qitem => qitem.Income) ?? 0,
                        OrderCount = tempSubList?.Sum(qitem => qitem.OrderCount) ?? 0,
                        UserCount = tempSubList?.GroupBy(qitem => new { qitem.UserId }).Count() ?? 0,
                    });
                }
            }
            var obj = new
            {
                //支付订单数
                OrderCount = list?.Sum(qitem => qitem.OrderCount) ?? 0,
                //支付金额
                Income = list?.Sum(qitem => qitem.Income) ?? 0,

                //支付人数
                UserCount = list?.GroupBy(qitem => new { qitem.UserId }).Count() ?? 0,
                //支付件数
                GoodCount = list?.Sum(qitem => qitem.GoodCount) ?? 0,
                subList,
            };
            return obj;
        }

        /// <summary>
        /// 商品购买力TOP排行
        /// </summary>
        /// <param name="query"></param>
        public List<MallSalesGoodsTop> MallIndesSalesIncomeStatisticsModule(StatisticsQuery query)
        {
            return mallStatisticsRepository.MallIndesSalesIncomeStatisticsRepository(query);
        }


        /// <summary>
        /// 用户购买力TOP排行
        /// </summary>
        /// <param name="query"></param>
        public List<MallSalesUserTop> MallIndesSalesUserStatisticsModule(StatisticsQuery query)
        {
            return mallStatisticsRepository.MallIndesSalesUserStatisticsRepository(query);
        }
        #endregion

        /// <summary>
        /// 分销用户总计
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public object MallDistributorStatisticsModule(StatisticsQuery query)
        {
            return mallStatisticsRepository.MallDistributorStatisticsRepository(query);
        }

        /// <summary>
        /// 每日用户统计
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public object MallDistributorDayStatisticsModule(int pageIndex, int pageSize, out long rowsCount, StatisticsQuery query)
        {
            return mallStatisticsRepository.MallDistributorDayStatisticsRepository(pageIndex, pageSize, out rowsCount, query);
        }

        #region 直播配置

        /// <summary>
        /// 获取直播配置实体
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public RB_Live_Config_Extend GetLiveConfigModule(RB_Live_Config_Extend query)
        {
            return live_ConfigRepository.GetLiveConfigRepository(query);
        }

        /// <summary>
        /// 新增修改直播配置
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetLiveConfigModule(RB_Live_Config_Extend extModel)
        {
            var oldModel = GetLiveConfigModule(extModel);
            bool flag;
            if (oldModel != null && oldModel.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_Live_Config_Extend.LiveBgImg),extModel.LiveBgImg},
                    { nameof(RB_Live_Config_Extend.LiveQrCodeSize),extModel.LiveQrCodeSize},
                    { nameof(RB_Live_Config_Extend.LiveQrCodePaddingTop),extModel.LiveQrCodePaddingTop},
                    { nameof(RB_Live_Config_Extend.LiveQrCodePaddingLeft),extModel.LiveQrCodePaddingLeft},
                    { nameof(RB_Live_Config_Extend.LiveQrCodeType),extModel.LiveQrCodeType},
                };
                flag = live_ConfigRepository.Update(fileds, new WhereHelper(nameof(RB_Live_Config_Extend.Id), extModel.Id));
            }
            else
            {
                flag = live_ConfigRepository.Insert(extModel) > 0;
            }
            return flag;
        }
        #endregion
    }
}
