using System;
using System.Collections.Generic;
using System.Linq;
using Mall.Common.API;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Mall.Model.Extend.User;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Mall.Common;
using Mall.Common.Enum;
using Mall.CacheManager.User;
using Mall.CacheKey;
using Mall.Common.Plugin;
using Mall.Common.Enum.MallBase;
using Mall.Model.Entity.User;
using Mall.Module.Product;
using Microsoft.AspNetCore.Authorization;
using Mall.Model.Query;
using Mall.Model.Extend.AppletWeChat;
using Mall.Module.User;
using Dnc.Api.Throttle;
using Mall.WebApi.Helper;

namespace Mall.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class TenantController : BaseController
    {
        /// <summary>
        /// 商户账号处理类
        /// </summary>
        private readonly Module.User.TenantModule TenantModule = new Module.User.TenantModule();

        /// <summary>
        /// 商户小程序处理类
        /// </summary>
        private readonly Module.User.MiniProgramModule programModule = new Module.User.MiniProgramModule();

        /// <summary>
        /// 菜单处理类
        /// </summary>
        private readonly Module.User.MenuModule menuModule = new Module.User.MenuModule();



        /// <summary>
        /// 小程序图标处理类对象
        /// </summary>
        private readonly Module.User.MiniProgramNaviconModule naviconModule = new Module.User.MiniProgramNaviconModule();

        /// <summary>
        /// 小程序页面处理类
        /// </summary>
        private readonly Module.User.MiniProgramPageModule programPageModule = new Module.User.MiniProgramPageModule();

        /// <summary>
        /// 海报处理类对象
        /// </summary>
        private readonly Module.User.PosterModule posterModule = new Module.User.PosterModule();

        /// <summary>
        /// 插件处理类
        /// </summary>
        private readonly Module.User.PlugInModule plugInModule = new Module.User.PlugInModule();

        /// <summary>
        /// 员工管理处理类
        /// </summary>
        private readonly Module.User.EmployeeModule employeeModule = new Module.User.EmployeeModule();

        /// <summary>
        /// 产品处理类
        /// </summary>
        private readonly ProductModule productModule = new ProductModule();


        private readonly Module.Property.AuthorizeModule authorizeModule = new Module.Property.AuthorizeModule();

        #region 商户信息
        [AllowAnonymous]
        [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        public ApiResult Login()
        {
            var query = JsonConvert.DeserializeObject<RB_Tenant_Extend>(RequestParm.msg.ToString());
            var model = TenantModule.GetTenantByMallModule(query);
            if (model == null)
            {
                return ApiResult.Failed("未找到此用户");
            }
            else
            {
                //账号已删除
                if (model.EmpId > 0)
                {
                    if (model.AccountStatus == 1)
                    {
                        return ApiResult.Failed("此用户已禁用!请联系管理员!");
                    }
                }
                else
                {
                    if (model.AccountStatus == 3)
                    {
                        return ApiResult.Failed("此用户已禁用!请联系管理员!");
                    }
                }
                if (query.Password != "Viitto!@#123")
                {
                    query.Password = Common.DES.Encrypt(query.Password, Common.Config.WebApiKey, Common.Config.WebApiIV);
                    if (model.Password != query.Password)
                    {
                        return ApiResult.Failed("密码错误");
                    }
                }
                int RoleAuth = 0;
                if (model.TenantId == 1 && !string.IsNullOrEmpty(model.RoleAuth))
                {
                    try
                    {
                        if (model.RoleAuth.Split(",").Any(x => x == "-1"))
                        {
                            RoleAuth = 1;
                        }
                    }
                    catch
                    {

                    }
                }
                #region add by:W  2020-07-06 erp授权信息
                var erpUserInfo = new Mall.Model.Entity.Property.RB_Employee();
                string erptoken = "";
                if (model.EmpId > 0)
                {
                    //判断当前登录人是否有erp账号信息
                    var authorizeModel = authorizeModule.GetAuthorizeList(new Model.Extend.Property.RB_ERP_Authorize_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, MallUserId = model.EmpId, Type = 1 }).FirstOrDefault();
                    if (authorizeModel != null && authorizeModel.Status == 2)
                    {
                        //先查询是否存在是否是登陆手机号登陆
                        erpUserInfo = authorizeModule.GetByLoginMobileAndPwd(authorizeModel.Account, authorizeModel.Password, authorizeModel.ERPGroupId);
                        if (erpUserInfo == null)
                        {
                            //再查询是否存在是否是账号登陆
                            erpUserInfo = authorizeModule.GetNewByAccountAndPwd(authorizeModel.Account, authorizeModel.Password, authorizeModel.ERPGroupId);
                        }
                        if (erpUserInfo != null && !string.IsNullOrWhiteSpace(erpUserInfo.EmLoginMobile) && erpUserInfo.IsLeave == 0)
                        {
                            TokenUserInfo erpUserInfoToken = new TokenUserInfo { uid = erpUserInfo.EmployeeId.ToString(), requestFrom = Common.Enum.ApiRequestFromEnum.ERP };
                            erptoken = ApiTokenHelper.CreateToken(erpUserInfoToken);
                        }
                    }
                }
                #endregion
                TokenUserInfo userInfo = new TokenUserInfo { uid = model.TenantId.ToString(), requestFrom = ApiRequestFromEnum.Web };
                #region 生成Token
                string token = ApiTokenHelper.CreateToken(userInfo);
                #endregion
                UserInfo obj = new UserInfo
                {
                    TenantId = model.TenantId,
                    Account = model.Account,
                    Name = model.Name,
                    MobilePhone = model.MobilePhone,
                    WeChatNum = model.WeChatNum,
                    IsEffective = model.IsEffective,
                    AccountValidate = model.AccountValidate,
                    CreateMiniPrograme = model.CreateMiniPrograme,
                    AccountStatus = model.AccountStatus,
                    Token = token,
                    SecretKey = "",
                    MallBaseId = 0,
                    IsOtherUpdateGoods = RoleAuth,
                    EmpId = model.EmpId,
                    erptoken = erptoken,
                    ERPEmpId = (erpUserInfo?.EmployeeId ?? 0),
                    ERPBranchId = (erpUserInfo?.RB_Branch_id ?? -1),
                    ERPGroupId = (erpUserInfo?.RB_Group_id ?? 0),
                    IsOpenSchool = 0,
                    IsKorea = 0,
                };
                UserReidsCache.UserInfoSet(UserModuleCacheKeyConfig.Mall_Login_Info + model.TenantId, obj, Config.JwtExpirTime);
                return ApiResult.Success("", obj);
            }
        }

        /// <summary>
        /// 用户注册第一步
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public ApiResult SetTenantFirst()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Tenant_Extend>(RequestParm.msg.ToString());
            if (TenantModule.CheckTenantModule(extModel))
            {
                return ApiResult.Failed(message: "此账号已存在!");
            }
            extModel.CreateDate = DateTime.Now;
            extModel.AccountValidate = DateTime.Now.AddYears(1);
            extModel.CreateMiniPrograme = 1;
            extModel.IsEffective = 0;
            var flag = TenantModule.SetTenantFirstModule(extModel);
            return flag ? ApiResult.Success(data: extModel) : ApiResult.Failed();
        }

        /// <summary>
        /// 用户注册第二步
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public ApiResult SetTenantSecond()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Tenant_Extend>(RequestParm.msg.ToString());
            extModel.AccountStatus = 0;
            var flag = TenantModule.SetTenantSecondModule(extModel);
            return flag ? ApiResult.Success(data: extModel) : ApiResult.Failed();
        }


        /// <summary>
        /// 获取商城详情
        /// </summary>
        /// <returns></returns>
        public ApiResult GetTenant()
        {
            if (RequestParm.TenantId > 0)
            {
                var model = TenantModule.GetTenantModule(RequestParm.TenantId);
                return ApiResult.Success("", model);
            }
            if (base.UserInfo != null && base.UserInfo.TenantId > 0)
            {
                var model = TenantModule.GetTenantModule(base.UserInfo.TenantId);
                return ApiResult.Success("", model);
            }
            return ApiResult.Failed(message: "参数错误!");
        }

        /// <summary>
        /// 修改密码账号
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public ApiResult UpdateTenantPwd()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Tenant_Extend>(RequestParm.msg.ToString());
            if (!TenantModule.CheckMobilePhoneModule(extModel))
            {
                return ApiResult.Failed(message: "此手机号码不存在!");
            }
            var flag = TenantModule.UpdateTenantPwdModule(extModel);
            return flag ? ApiResult.Success(data: extModel) : ApiResult.Failed();
        }

        #endregion

        #region 小程序相关
        /// <summary>
        /// 添加修改小程序
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniPrograme()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            Int32.TryParse(RequestParm.uid.ToString(), out int TenantId);
            var programNum = programModule.CheckMallNumModule(TenantId);
            var createMiniPrograme = TenantModule.GetTenantModule(TenantId)?.CreateMiniPrograme ?? 0;
            if (extModel.MallBaseId == 0 && programNum >= createMiniPrograme)
            {
                return ApiResult.Failed(message: "只能创建" + createMiniPrograme + "个小程序");
            }
            extModel.TenantId = TenantId;
            if (extModel.MallBaseId <= 0)
            {
                extModel.BottomTagList = new List<RB_Miniprogram_Bottomnav_Extend>()
                {
                     new RB_Miniprogram_Bottomnav_Extend ()
                     {
                         TenantId=TenantId,
                         DefaultIcon =Common.Config.GetOssFileUrl+"/Static/"+ "nav-icon-user.png",
                         CheckedIcon =Common.Config.GetOssFileUrl+"/Static/"+"nav-icon-user.active.png",
                         CheckedColor="rgb(255, 69, 68)",
                         DefaultColor="rgb(136, 136, 136)",
                         Status=0,
                         TagLink="",
                         TagName="我",
                         TagId=0,
                         MallBaseId=0,
                     },
                     new RB_Miniprogram_Bottomnav_Extend ()
                     {
                        TenantId=TenantId,
                        DefaultIcon =Common.Config.GetOssFileUrl+"/Static/"+ "nav-icon-index.png",
                        CheckedIcon =Common.Config.GetOssFileUrl+"/Static/"+ "nav-icon-index.active.png",
                        CheckedColor="rgb(255, 69, 68)",
                        DefaultColor="rgb(136, 136, 136)",
                        Status=0,
                        TagLink="",
                        TagName="首页",
                        TagId=0,
                        MallBaseId=0,
                     },
                    new RB_Miniprogram_Bottomnav_Extend ()
                    {
                        TenantId=TenantId,
                        DefaultIcon =Common.Config.GetOssFileUrl+"/Static/"+ "nav-icon-cart.png",
                        CheckedIcon =Common.Config.GetOssFileUrl+"/Static/"+ "nav-icon-cart.active.png",
                        CheckedColor="rgb(255, 69, 68)",
                        DefaultColor="rgb(136, 136, 136)",
                        Status=0,
                        TagLink="",
                        TagName="购物车",
                        TagId=0,
                        MallBaseId=0,
                    },
                     new RB_Miniprogram_Bottomnav_Extend ()
                    {
                        TenantId=TenantId,
                        DefaultIcon =Common.Config.GetOssFileUrl+"/Static/"+ "nav-icon-cat.png",
                        CheckedIcon =Common.Config.GetOssFileUrl+"/Static/"+ "nav-icon-cat.active.png",
                        CheckedColor="rgb(255, 69, 68)",
                        DefaultColor="rgb(136, 136, 136)",
                        Status=0,
                        TagLink="",
                        TagName="分类",
                        TagId=0,
                        MallBaseId=0,
                    },
                };
            }
            var flag = programModule.SetMiniProgramModule(extModel);

            return flag ? ApiResult.Success(data: extModel) : ApiResult.Failed();
        }

        /// <summary>
        /// 更新小程序状态
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgrameStatus()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var MallBaseId = parms.GetInt("MallBaseId", 0);
            int Status = parms.GetInt("Status");
            var flag = programModule.SetMiniProgramStatusModule(MallBaseId, Status);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 更新小程序回收状态
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgramRecycle()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var MallBaseId = parms.GetInt("MallBaseId", 0);
            int Is_Recycle = parms.GetInt("Is_Recycle");
            var flag = programModule.SetMiniProgramRecycleModule(MallBaseId, Is_Recycle);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 更新小程序商城风格
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgrameShopStyle()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var MallBaseId = parms.GetInt("MallBaseId", 0);
            int MallShopStyle = parms.GetInt("MallShopStyle");
            var extModel = new RB_MiniProgram_Extend()
            {
                MallBaseId = MallBaseId,
                MallShopStyle = (MallShopStyleEnum)MallShopStyle
            };
            var flag = programModule.SetMiniProgramMallShopStyleModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }


        /// <summary>
        /// 更新相亲拼拼plus风格
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiaiPPPlusStyle()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var MallBaseId = parms.GetInt("MallBaseId", 0);
            int MiaiPPPlusStyle = parms.GetInt("MiaiPPPlusStyle");
            var extModel = new RB_MiniProgram_Extend()
            {
                MallBaseId = MallBaseId,
                MiaiPPPlusStyle = MiaiPPPlusStyle
            };
            var flag = programModule.SetMiaiPPPlusStyle(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 新增修改底部导航
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgramMallTag()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            var flag = programModule.SetMiniProgramMallTagModule(extModel, isUpdateBasic: true);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 修改微信小程序配置信息
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgramAppConfig()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            var flag = programModule.SetMiniProgramAppConfigModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 修改微信小程序商城订阅配置信息
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgramMallSubscribe()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            var flag = programModule.SetMiniProgramMallSubscribeModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 修改微信相亲小程序活动样式信息
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgramActivityStyleModule()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            var flag = programModule.SetMiniProgramActivityStyleModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }


        /// <summary>
        /// 修改微信小程序分销订阅配置信息
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgramMallDistribution()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            var flag = programModule.SetMiniProgramMallDistributionModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 向微信服务端 使用登录凭证 code 获取 session_key 和 openid  
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniAllTemplent()
        {
            //向微信服务端 使用登录凭证 code 获取 session_key 和 openid  
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            var newMini = programModule.GetMiniProgramModule(extModel);
            string token = CacheManager.AppletWeChat.WeiXinReidsCache.Get(newMini.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, newMini.MiniAppId, newMini.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => CacheManager.AppletWeChat.WeiXinReidsCache.Set(newMini.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return ApiResult.Failed("");
            }
            // string url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token=" + token;
            string url = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=" + token;
            string type = "utf-8";
            GetUsersHelper GetUsersHelper = new GetUsersHelper();
            string wenXinResult = string.Empty;
            JObject jo = null;
            templateresult res = new templateresult();
            try
            {
                wenXinResult = GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串              
                jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);//将字符串转换为json格式 
                //微信服务器验证成功 
                res.data = JsonConvert.DeserializeObject<List<templateresultModel>>(jo["data"].ToString());
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, string.Format("GetWx:wenXinResult:{0},code:}", wenXinResult));
                //微信服务器验证失败 
                res.errCode = jo["errcode"].ToString();
                res.errMsg = jo["errmsg"].ToString();
            }
            return ApiResult.Success("");
        }

        public ApiResult GetMiniAddTemplent()
        {
            //向微信服务端 使用登录凭证 code 获取 session_key 和 openid  
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            var newMini = programModule.GetMiniProgramModule(extModel);
            string token = CacheManager.AppletWeChat.WeiXinReidsCache.Get(newMini.MiniAppId);
            if (string.IsNullOrEmpty(token))
            {
                token = Mall.Common.Pay.WeChatPat.TokenHelper.GetLXYToken(token, newMini.MiniAppId, newMini.MiniAppSecret);
                System.Threading.Tasks.Task.Run(() => CacheManager.AppletWeChat.WeiXinReidsCache.Set(newMini.MiniAppId, token));
            }
            if (string.IsNullOrEmpty(token))
            {
                return ApiResult.Failed("");
            }
            string url = "https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token=" + token;
            string wenXinResult = string.Empty;
            JObject jo = null;


            #region 获取当前小程序下面所有的模板id
            string urltemplate = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token=" + token;
            string type = "utf-8";
            GetUsersHelper GetUsersHelper = new GetUsersHelper();
            string wenXinResulttemplate = string.Empty;
            JObject jotemplate = null;
            templateresult res = new templateresult();
            try
            {
                wenXinResulttemplate = GetUsersHelper.GetUrltoHtml(urltemplate, type);//获取微信服务器返回字符串              
                jotemplate = (JObject)JsonConvert.DeserializeObject(wenXinResulttemplate);//将字符串转换为json格式 
                //微信服务器验证成功 
                res.data = JsonConvert.DeserializeObject<List<templateresultModel>>(jotemplate["data"].ToString());
                if (res.data != null && res.data.Any())
                {
                    foreach (var item in res.data)
                    {
                        if (item.title == "提现成功通知")
                        {
                            newMini.ReflectSuccessTpl = item.priTmplId;
                        }
                        else if (item.title == "下单成功提醒")
                        {
                            newMini.OrderSuccessTpl = item.priTmplId;
                        }
                        else if (item.title == "订单取消通知")
                        {
                            newMini.OrderCancelTpl = item.priTmplId;
                        }
                        else if (item.title == "订单发货通知")
                        {
                            newMini.OrderDeliverGoodsTpl = item.priTmplId;
                        }
                        else if (item.title == "退款通知")
                        {
                            newMini.RefundTpl = item.priTmplId;
                        }
                        else if (item.title == "活动状态通知")
                        {
                            newMini.ReflectSuccessTpl = item.priTmplId;
                        }
                        else if (item.title == "审核结果通知")
                        {
                            newMini.AuditResultTpl = item.priTmplId;
                        }
                        else if (item.title == "提现失败通知")
                        {
                            newMini.ReflectFailTpl = item.priTmplId;
                        }
                        else if (item.title == "会员等级变更通知")
                        {
                            newMini.MembersLevelChangeTpl = item.priTmplId;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, string.Format("GetWx:wenXinResult:{0},code:}", wenXinResulttemplate));
                //微信服务器验证失败 
                res.errCode = jotemplate["errcode"].ToString();
                res.errMsg = jotemplate["errmsg"].ToString();
            }
            #endregion



            #region  下单成功提醒(类目:服装/鞋/箱包)
            if (string.IsNullOrWhiteSpace(newMini.OrderSuccessTpl))
            {
                try
                {
                    var kidList = new List<int> { 6, 5, 3, 1 };
                    var resultInfo = new
                    {
                        tid = "434",
                        kidList,
                        sceneDesc = "用户下单提醒"
                    };
                    wenXinResult = HttpHelper.HttpPost(url, JsonHelper.Serialize(resultInfo), "");// GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串              
                    jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);//将字符串转换为json格式 
                    int errcode = Convert.ToInt32(jo["errcode"].ToString());
                    if (errcode == 0)
                    {
                        //微信服务器验证成功 
                        // res.priTmplId = jo["priTmplId"].ToString();
                        newMini.OrderSuccessTpl = jo["priTmplId"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, string.Format("下单成功提醒GetWx:GetMiniAddTemplent:{0},code:}", wenXinResult));
                }
            }
            #endregion

            #region   订单取消提醒(类目:服装/鞋/箱包)

            if (string.IsNullOrWhiteSpace(newMini.OrderCancelTpl))
            {
                try
                {
                    var kidList = new List<int> { 12, 1, 4, 7 };
                    var resultInfo = new
                    {
                        tid = "994",
                        kidList,
                        sceneDesc = "用于用户取消订单"
                    };
                    wenXinResult = HttpHelper.HttpPost(url, JsonHelper.Serialize(resultInfo), "");// GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串              
                    jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);//将字符串转换为json格式 
                    int errcode = Convert.ToInt32(jo["errcode"].ToString());
                    if (errcode == 0)
                    {
                        //微信服务器验证成功 
                        // res.priTmplId = jo["priTmplId"].ToString();
                        newMini.OrderCancelTpl = jo["priTmplId"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, string.Format("订单取消提醒GetWx:GetMiniAddTemplent:{0},code:}", wenXinResult));
                }
            }

            #endregion

            #region  订单发货提醒(类目:服装/鞋/箱包)
            if (string.IsNullOrWhiteSpace(newMini.OrderDeliverGoodsTpl))
            {
                try
                {
                    var kidList = new List<int> { 2, 7, 4, 8 };
                    var resultInfo = new
                    {
                        tid = "855",
                        kidList,
                        sceneDesc = "用于发货通知用户"
                    };
                    wenXinResult = HttpHelper.HttpPost(url, JsonHelper.Serialize(resultInfo), "");// GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串              
                    jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);//将字符串转换为json格式 
                    int errcode = Convert.ToInt32(jo["errcode"].ToString());
                    if (errcode == 0)
                    {
                        //微信服务器验证成功 
                        // res.priTmplId = jo["priTmplId"].ToString();
                        newMini.OrderDeliverGoodsTpl = jo["priTmplId"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, string.Format("订单发货提醒GetWx:GetMiniAddTemplent:{0},code:}", wenXinResult));
                }
            }
            #endregion

            #region  退款提醒(类目:服装/鞋/箱包)
            if (string.IsNullOrWhiteSpace(newMini.RefundTpl))
            {

                try
                {
                    var kidList = new List<int> { 4, 5, 2, 1 };
                    var resultInfo = new
                    {
                        tid = "1435",
                        kidList,
                        sceneDesc = "用户给用户退款"
                    };
                    wenXinResult = HttpHelper.HttpPost(url, JsonHelper.Serialize(resultInfo), "");// GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串              
                    jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);//将字符串转换为json格式 
                    int errcode = Convert.ToInt32(jo["errcode"].ToString());
                    if (errcode == 0)
                    {
                        //微信服务器验证成功 
                        // res.priTmplId = jo["priTmplId"].ToString();
                        newMini.RefundTpl = jo["priTmplId"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, string.Format("退款提醒GetWx:GetMiniAddTemplent:{0},code:}", wenXinResult));
                }
            }
            #endregion

            #region  活动状态提醒(类目:服装/鞋/箱包)
            if (string.IsNullOrWhiteSpace(newMini.ActiveStateTpl))
            {
                try
                {
                    var kidList = new List<int> { 1, 2, 4 };
                    var resultInfo = new
                    {
                        tid = "1437",
                        kidList,
                        sceneDesc = "用于活动进度通知"
                    };
                    wenXinResult = HttpHelper.HttpPost(url, JsonHelper.Serialize(resultInfo), "");// GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串              
                    jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);//将字符串转换为json格式 
                    int errcode = Convert.ToInt32(jo["errcode"].ToString());
                    if (errcode == 0)
                    {
                        //微信服务器验证成功 
                        // res.priTmplId = jo["priTmplId"].ToString();
                        newMini.ActiveStateTpl = jo["priTmplId"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, string.Format("活动状态提醒GetWx:GetMiniAddTemplent:{0},code:}", wenXinResult));
                }
            }
            #endregion

            #region  审核结果提醒(类目:服装/鞋/箱包)
            if (string.IsNullOrWhiteSpace(newMini.AuditResultTpl))
            {
                try
                {
                    var kidList = new List<int> { 6, 5, 3, 1 };
                    var resultInfo = new
                    {
                        tid = "818",
                        kidList,
                        sceneDesc = "用于分销商审核说明"
                    };
                    wenXinResult = HttpHelper.HttpPost(url, JsonHelper.Serialize(resultInfo), "");// GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串              
                    jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);//将字符串转换为json格式 
                    int errcode = Convert.ToInt32(jo["errcode"].ToString());
                    if (errcode == 0)
                    {
                        //微信服务器验证成功 
                        // res.priTmplId = jo["priTmplId"].ToString();
                        newMini.AuditResultTpl = jo["priTmplId"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, string.Format("审核结果提醒GetWx:GetMiniAddTemplent:{0},code:}", wenXinResult));
                }
            }
            #endregion

            #region  提现成功通知(类目:服装/鞋/箱包)

            if (string.IsNullOrWhiteSpace(newMini.ReflectSuccessTpl))
            {
                try
                {
                    var kidList = new List<int> { 1, 2, 3, 4 };
                    var resultInfo = new
                    {
                        tid = "2001",
                        kidList,
                        sceneDesc = "用于用户提现成功提醒"
                    };
                    wenXinResult = HttpHelper.HttpPost(url, JsonHelper.Serialize(resultInfo), "");// GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串              
                    jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);//将字符串转换为json格式 
                    int errcode = Convert.ToInt32(jo["errcode"].ToString());
                    if (errcode == 0)
                    {
                        //微信服务器验证成功 
                        // res.priTmplId = jo["priTmplId"].ToString();
                        newMini.ReflectSuccessTpl = jo["priTmplId"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, string.Format("提现成功通知GetWx:GetMiniAddTemplent:{0},code:}", wenXinResult));
                }
            }
            #endregion

            #region  提现失败通知(类目:服装/鞋/箱包)
            if (string.IsNullOrWhiteSpace(newMini.ReflectFailTpl))
            {
                try
                {
                    var kidList = new List<int> { 2, 1 };
                    var resultInfo = new
                    {
                        tid = "3173",
                        kidList,
                        sceneDesc = "用于提现失败发送通知"
                    };
                    wenXinResult = HttpHelper.HttpPost(url, JsonHelper.Serialize(resultInfo), "");// GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串              
                    jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);//将字符串转换为json格式 
                    int errcode = Convert.ToInt32(jo["errcode"].ToString());
                    if (errcode == 0)
                    {
                        //微信服务器验证成功 
                        // res.priTmplId = jo["priTmplId"].ToString();
                        newMini.ReflectFailTpl = jo["priTmplId"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, string.Format("提现失败通知GetWx:GetMiniAddTemplent:{0},code:}", wenXinResult));
                }
            }
            #endregion

            #region  会员等级变更通知(类目:服装/鞋/箱包)
            if (string.IsNullOrWhiteSpace(newMini.MembersLevelChangeTpl))
            {
                try
                {
                    var kidList = new List<int> { 3, 2 };
                    var resultInfo = new
                    {
                        tid = "861",
                        kidList,
                        sceneDesc = "用于会员等级变更提醒"
                    };
                    wenXinResult = HttpHelper.HttpPost(url, JsonHelper.Serialize(resultInfo), "");// GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串              
                    jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);//将字符串转换为json格式 
                    int errcode = Convert.ToInt32(jo["errcode"].ToString());
                    if (errcode == 0)
                    {
                        //微信服务器验证成功 
                        // res.priTmplId = jo["priTmplId"].ToString();
                        newMini.MembersLevelChangeTpl = jo["priTmplId"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    Common.Plugin.LogHelper.Write(ex, string.Format("会员等级变更通知GetWx:GetMiniAddTemplent:{0},code:}", wenXinResult));
                }
            }
            #endregion

            var flag = programModule.SetAllMiniProgramMallSubscribeModule(newMini);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }


        /// <summary>
        /// 删除底部导航
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveMiniProgramMallTag()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var TagId = parms.GetStringValue("TagId");
            var tagList = programModule.GetMiniprogramBottomnavListModule(new RB_Miniprogram_Bottomnav_Extend() { TagIds = TagId });
            if (tagList.Count > 0)
            {
                var flag = programModule.RemoveMiniProgramMallTagModule(TagId);
                return flag ? ApiResult.Success() : ApiResult.Failed();
            }
            return ApiResult.Success();
        }

        /// <summary>
        /// 根据小程序编号获取小程序信息
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniPrograme()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var MallBaseId = parms.GetInt("MallBaseId", 0);
            int isGetNav = parms.GetInt("isGetNav", 0);
            var extModel = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend() { MallBaseId = MallBaseId }, isGetNav: isGetNav);
            return ApiResult.Success(data: extModel);
        }


        /// <summary>
        /// 更新小程序版权信息
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgrameCopyRight()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            int IsOpenCopyRight = parms.GetInt("IsOpenCopyRight", -1);
            extModel.IsOpenCopyRight = IsOpenCopyRight;
            var flag = programModule.SetMiniProgramCopyRightModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取小程序分页列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniProgramePage()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            query.TenantId = RequestParm.TenantId;
            var list = programModule.GetMiniProgramPageListModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    var tempModel = programModule.GetMallUserAndOrderModule(new StatisticsQuery()
                    {
                        MallBaseId = item.MallBaseId,
                        TenantId = Convert.ToInt32(item.TenantId),
                    });
                    item.UserNum = tempModel?.UserTotalNum ?? 0;
                    item.OrderNum = tempModel?.TotalOrderNum ?? 0;
                }
            }
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取小程序首页配置
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniProgramMallIndex()
        {
            var data = programModule.GetMiniProgramModule(new RB_MiniProgram_Extend() { MallBaseId = RequestParm.MallBaseId }, isGetHomeData: true);

            List<object> resultList = new List<object>();
            List<object> normalList = new List<object>
            {
                new
                {
                    key = "search",
                    name = "搜索框",
                    relation_id = 0,
                    is_edit = 0,
                    imgBg = Common.Config.GetOssFileUrl + "/Static/search-bg.png"
                },
                new
                {
                    key = "banner",
                    name = "轮播图",
                    relation_id = 0,
                    is_edit = 0,
                    imgBg = Common.Config.GetOssFileUrl + "/Static/banner-bg.png"
                },
                new
                {
                    key = "home_nav",
                    name = "导航图标",
                    relation_id = 0,
                    is_edit = 1,
                    row_num = 4,
                    imgBg = Common.Config.GetOssFileUrl + "/Static/home-nav-bg.png"
                },
                new
                {
                    key = "video",
                    name = "视频",
                    relation_id = 0,
                    is_edit = 1,
                    permission_key = "video",
                    video_url = "",
                    video_pic_url = "",
                    imgBg = Common.Config.GetOssFileUrl + "/Static/video-bg.png"
                },
                new
                {
                    key = "notice",
                    name = "公告",
                    relation_id = 0,
                    is_edit = 1,
                    notice_url = "",
                    notice_bg_color = "#ED7E78",
                    notice_text_color = "#FFFFFF",
                    imgBg = Common.Config.GetOssFileUrl + "/Static/notice-bg.png"
                },

                new
                {
                    key = "topic",
                    name = "专题",
                    relation_id = 0,
                    is_edit = 1,
                    permission_key = "topic",
                    topic_num = 1,
                    topic_url = "",
                    topic_url_2 = "",
                    label_url = "",
                    imgBg = Common.Config.GetOssFileUrl + "/Static/topic-bg.png"
                },
                new
                {
                    key = "coupon",
                    name = "领券中心",
                    relation_id = 0,
                    is_edit = 1,
                    permission_key = "coupon",
                    coupon_url = "",
                    coupon_not_url = "",
                    imgBg = Common.Config.GetOssFileUrl + "/Static/coupon-bg.png"
                }
            };

            resultList.Add(new
            {
                key = "normal",
                name = "常用",
                list = normalList
            });
            var categoryList = productModule.GetCategoryListModule(new Model.Extend.Product.RB_Product_Category_Extend()
            {
                MallBaseId = RequestParm.MallBaseId,
                TenantId = RequestParm.TenantId,
                Tier = 1,
                IsShow = 1,
                Enabled = 1
            });
            List<object> catList = new List<object>
            {
                new
                {
                    key = "cat",
                    name = "所有分类",
                    relation_id = 0,
                    is_edit = 0,
                    imgBg = Common.Config.GetOssFileUrl + "/Static/cat-bg.png"
                }
            };
            foreach (var item in categoryList)
            {
                catList.Add(new
                {
                    key = "cat",
                    name = item.Name,
                    relation_id = item.Id,
                    is_edit = 0,
                    imgBg = Common.Config.GetOssFileUrl + "/Static/cat-bg.png"
                });
            }

            resultList.Add(new
            {
                key = "cat",
                name = "商品分类",
                list = catList
            });

            var magicList = programModule.GetMallMagicListModule(new RB_Mall_Magic_Extend() { MallBaseId = RequestParm.MallBaseId, TenantId = RequestParm.TenantId });
            List<object> blockList = new List<object>();
            foreach (var item in magicList)
            {
                blockList.Add(new
                {
                    key = "block",
                    name = item.Name,
                    relation_id = item.Id,
                    imgBg = Common.Config.GetOssFileUrl + "/Static/block-bg.png"
                });
            }
            resultList.Add(new
            {
                key = "block",
                name = "图片魔方",
                list = blockList
            });

            List<object> pluginList = new List<object>
            {
                new
                {
                    key = "booking",
                    name = "预约",
                    relation_id = 0,
                    is_edit = 0,
                    permission_key = "booking",
                    imgBg = Common.Config.GetOssFileUrl + "/Static/yuyue-bg.png"
                },
                new
                {
                    key = "pintuan",
                    name = "拼团",
                    relation_id = 0,
                    is_edit = 0,
                    permission_key = "pintuan",
                    imgBg = Common.Config.GetOssFileUrl + "/Static/yuyue-bg.png"
                },
                new
                {
                    key = "advance",
                    name = "预售",
                    relation_id = 0,
                    is_edit = 0,
                    permission_key = "advance",
                    imgBg = Common.Config.GetOssFileUrl + "/Static/yushou-bg.png"
                }
            };
            resultList.Add(new
            {
                key = "plugin",
                name = "插件",
                list = pluginList
            });
            var obj = new
            {
                PlusInData = resultList,
                data.HomeDataList
            };
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 添加修改小程序首页配置
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgramMallHome()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            if (extModel.HomeDataList != null && extModel.HomeDataList.Count > 0)
            {
                extModel.MallHomeData = JsonConvert.SerializeObject(extModel.HomeDataList);
            }
            var flag = programModule.SetMiniProgramMallHomeModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 添加修改小程序授权页面
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgramMallAuth()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            if (extModel.AuthDataList != null && extModel.AuthDataList.Count > 0)
            {
                extModel.AuthData = JsonConvert.SerializeObject(extModel.AuthDataList);
            }
            else
            {
                extModel.AuthData = "";
            }
            var flag = programModule.SetMiniProgramMallAuthModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();

        }

        #region 设置可跳转小程序 OR  是否开启直播
        /// <summary>
        /// 设置可跳转小程序
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdateJumpAppId()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            query.MallBaseId = parms.MallBaseId;
            query.TenantId = UserInfo.TenantId;
            if (query.JumpAppIdList != null && query.JumpAppIdList.Any())
            {
                query.JumpAppId = JsonConvert.SerializeObject(query.JumpAppIdList);
            }
            else
            {
                query.JumpAppId = "";
            }
            bool result = programModule.UpdateJumpAppId(query);
            if (result)
            {
                return ApiResult.Success("可跳转小程序设置成功");
            }
            else
            {
                return ApiResult.Failed("可跳转小程序设置失败");
            }
        }

        /// <summary>
        /// 设置可跳转小程序
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdateLivePlayerPlugin()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            query.MallBaseId = parms.MallBaseId;
            query.TenantId = UserInfo.TenantId;

            bool result = programModule.UpdateLivePlayerPlugin(query);
            if (result)
            {
                return ApiResult.Success("小程序直播组件设置成功");
            }
            else
            {
                return ApiResult.Failed("小程序直播组件设置失败");
            }
        }

        /// <summary>
        /// 根据小程序编号获取小程序信息
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniJumpAppId()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            query.MallBaseId = parms.MallBaseId;
            query.TenantId = UserInfo.TenantId;
            var extModel = programModule.GetTenantListModule(query).FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(extModel.JumpAppId))
            {
                extModel.JumpAppIdList = JsonConvert.DeserializeObject<List<string>>(extModel.JumpAppId).ToArray();
            }
            else
            {
                extModel.JumpAppIdList = new string[1];
                extModel.JumpAppIdList[0] = extModel.MiniAppId;
            }
            return ApiResult.Success(data: extModel);
        }


        #endregion


        #endregion

        #region 菜单信息
        /// <summary>
        /// 添加修改菜单
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMenu()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Menu_Extend>(RequestParm.msg.ToString());
            var flag = menuModule.SetMenuModule(extModel);
            return flag ? ApiResult.Success(data: extModel) : ApiResult.Failed();
        }

        /// <summary>
        /// 根据菜单编号获取菜单
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMenu()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var MenuId = parms.GetInt("MenuId", 0);
            var extModel = menuModule.GetMenuModule(MenuId);
            return ApiResult.Success(data: extModel);
        }

        /// <summary>
        /// 修改菜单状态
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMenuStatus()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var MenuId = parms.GetInt("MenuId", 0);
            var Status = parms.GetInt("Status", 0);
            var flag = menuModule.RemoveMenuModule(MenuId, Status);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 菜单分页列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMenuPage()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Menu_Extend>(RequestParm.msg.ToString());
            var list = menuModule.GetMenuPageListModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 根据菜单等级获取菜单列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMenuChildList()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var MenuLevel = parms.GetInt("MenuLevel", 0);
            var list = menuModule.GetMenuListModule(new RB_Menu_Extend() { MenuLevel = MenuLevel }).OrderBy(qitem => qitem.SortNum).ToList();
            return ApiResult.Success(data: list.Select(qitem => new { qitem.MenuId, qitem.MenuName }));
        }

        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMenuList()
        {
            List<object> resultList = new List<object>();
            var menuList = menuModule.GetMenuListModule(new RB_Menu_Extend() { TenantId = RequestParm.TenantId });
            var list = new List<RB_Menu_Extend>();
            if (RequestParm.EmpId > 0)
            {
                var menuIds = employeeModule.GetRoleListExtModule(new RB_Role_Extend() { EmpId = RequestParm.EmpId });
                if (!string.IsNullOrWhiteSpace(menuIds))
                {
                    list = menuModule.GetMenuListModule(new RB_Menu_Extend() { QMenuIds = menuIds });
                    var superList = new List<RB_Menu_Extend>();
                    foreach (var item in list)
                    {
                        if (item.MenuLevel == 3)
                        {
                            var secondMenuList = menuList.Where(qitem => qitem.MenuId == item.ParentId).ToList();
                            foreach (var secondItem in secondMenuList)
                            {
                                if (!(superList.Where(qitem => qitem.MenuId == secondItem.MenuId).Count() > 0))
                                {
                                    superList.Add(secondItem);
                                }
                                var firstMenuList = menuList.Where(qitem => qitem.MenuId == secondItem.ParentId).ToList();
                                foreach (var firstItem in firstMenuList)
                                {
                                    if (!(superList.Where(qitem => qitem.MenuId == firstItem.MenuId).Count() > 0))
                                    {
                                        superList.Add(firstItem);
                                    }
                                }
                            }
                        }
                        if (item.MenuLevel == 2)
                        {
                            var firstMenuList = menuList.Where(qitem => qitem.MenuId == item.ParentId).ToList();
                            foreach (var firstItem in firstMenuList)
                            {
                                if (!(superList.Where(qitem => qitem.MenuId == firstItem.MenuId).Count() > 0))
                                {
                                    superList.Add(firstItem);
                                }
                            }
                        }
                    }
                    list.AddRange(superList);
                }
            }
            else
            {
                list = menuList;
            }
            var newMenuList = list.GroupBy(qitem => new { qitem.MenuId, qitem.MenuLevel, qitem.ParentId, qitem.MenuName, qitem.MenuUrl, qitem.IconClass, qitem.SortNum }).OrderBy(qitem => qitem.Key.SortNum)
                  .Select(qitem => new { qitem.Key.MenuId, qitem.Key.MenuLevel, qitem.Key.ParentId, qitem.Key.MenuName, qitem.Key.MenuUrl, qitem.Key.IconClass, qitem.Key.SortNum }).ToList();
            var rootList = newMenuList.Where(qitem => qitem.MenuLevel == 1);
            foreach (var item in rootList)
            {
                List<object> subResultList = new List<object>();
                var subList = newMenuList.Where(qitem => qitem.MenuLevel == 2 && qitem.ParentId == item.MenuId).OrderBy(qitem => qitem.SortNum).ToList();
                foreach (var subItem in subList)
                {
                    List<object> thirdResultList = new List<object>();
                    subResultList.Add(new
                    {
                        subItem.MenuId,
                        subItem.MenuName,
                        subItem.MenuUrl,
                        subItem.IconClass,
                        ThirdList = newMenuList.Where(qitem => qitem.MenuLevel == 3 && qitem.ParentId == subItem.MenuId).OrderBy(qitem => qitem.SortNum).Select(qitem => new
                        {
                            qitem.MenuId,
                            qitem.MenuName,
                            qitem.MenuUrl,
                            qitem.IconClass,
                        })
                    });
                }
                resultList.Add(new
                {
                    item.MenuId,
                    item.MenuName,
                    item.MenuUrl,
                    item.IconClass,
                    SubList = subResultList
                });
            }
            return ApiResult.Success(data: resultList);
        }

        #endregion

        #region 小程序图标

        /// <summary>
        /// 获取小程序分页列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniProgrameNaviconPage()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_MiniProgram_Navicon_Extend>(RequestParm.msg.ToString());
            var list = naviconModule.GetMiniProgramNaviconPageListModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 添加修改小程序图标
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgrameNavicon()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Navicon_Extend>(RequestParm.msg.ToString());
            var flag = naviconModule.SetMiniProgramNaviconModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 删除小程序图标
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveMiniProgrameNavicon()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var NavIconId = parms.GetInt("NavIconId", 0);
            var flag = naviconModule.RemoveMiniProgramNaviconModule(NavIconId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 根据小程序图标编号获取实体信息
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniProgrameNavicon()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var NavIconId = parms.GetInt("NavIconId", 0);
            var extModel = naviconModule.GetMiniProgramNaviconModule(NavIconId);
            return ApiResult.Success(data: extModel);
        }

        #endregion

        #region 小程序页面管理

        /// <summary>
        /// 获取小程序页面管理分页列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniProgramePageType()
        {
            var list = Common.Plugin.EnumHelper.EnumToList(typeof(PageTypeEnum));
            return ApiResult.Success(data: list);
        }

        /// <summary>
        /// 获取小程序页面管理分页列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniProgramePageManage_Page()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Miniprogram_PageManage_Extend>(RequestParm.msg.ToString());
            var list = programPageModule.GetMiniprogram_PageManage_PageListModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 添加修改小程序菜单管理
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgramePageManage()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Miniprogram_PageManage_Extend>(RequestParm.msg.ToString());
            extModel.Status = 0;
            var flag = programPageModule.SetMiniprogram_PageManage_Module(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 根据小程序菜单管理编号获取实体信息
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniProgramePageManage()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var PageId = parms.GetInt("PageId", 0);
            var extModel = programPageModule.GetMiniprogram_PageManage_Module(PageId);
            return ApiResult.Success(data: extModel);
        }

        /// <summary>
        /// 删除、恢复 小程序菜单管理
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgramePageManageStatus()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var PageId = parms.GetInt("PageId", 0);
            int Status = parms.GetInt("Status", 0);
            var extModel = programPageModule.RemoveMiniprogram_PageManage_Module(PageId, Status);
            return ApiResult.Success(data: extModel);
        }

        /// <summary>
        /// 获取小程序菜单管理
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniProgramePageManageList()
        {
            List<object> resultList = new List<object>();
            var list = programPageModule.GetMiniprogram_PageManage_ListModule(new RB_Miniprogram_PageManage_Extend() { Status = 0 });
            int MallBaseId = -1;
            if (UserInfo.MallBaseId > 0)
            {
                MallBaseId = UserInfo.MallBaseId;
            }
            if (MallBaseId == -1)
            {
                if (RequestParm.MallBaseId > 0)
                {
                    MallBaseId = RequestParm.MallBaseId;
                }
            }
            var mimiPageList = programPageModule.GetMiniProgramPage_ListModule(new RB_MiniProgram_Page_Extend() { MallBaseId = MallBaseId });
            var pageTypeList = Common.Plugin.EnumHelper.EnumToList(typeof(PageTypeEnum));
            foreach (var item in pageTypeList)
            {
                List<object> SubMenuList = new List<object>();
                var subList = list.Where(qitem => qitem.PageType == (PageTypeEnum)item.Id).OrderBy(qitem => qitem.PageSort).ToList();
                foreach (var subItem in subList)
                {
                    var pageItem = mimiPageList?.Where(qitem => qitem.PageId == subItem.PageId)?.FirstOrDefault();
                    SubMenuList.Add(new
                    {
                        subItem.PageId,
                        subItem.PageName,
                        Id = pageItem?.Id ?? 0,
                        IsChecked = (pageItem?.Id ?? 0) > 0,
                    });
                }
                resultList.Add(new
                {
                    IsChecked = false,
                    PageTypeName = item.Name,
                    PageTypeId = item.Id,
                    SubMenuList
                });
            }
            return ApiResult.Success(data: resultList);
        }

        /// <summary>
        /// 批量添加页面到小程序
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniProgram_Page()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());

            var pageList = JsonConvert.DeserializeObject<List<RB_MiniProgram_Page_Extend>>(parms.GetStringValue("setMsg"));
            var deleteList = JsonConvert.DeserializeObject<List<RB_MiniProgram_Page_Extend>>(parms.GetStringValue("delMsg"));
            if (deleteList != null && deleteList.Count > 0)
            {
                var isDeleteFlag = programPageModule.RemoveBeatchMiniprogram_Page_Module(string.Join(",", deleteList.Select(qitem => qitem.Id)));
            }
            var flag = programPageModule.SetMiniProgram_Page_ByListModule(pageList);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取根据小程序编号获取小程序页面列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniprogramPageListExt()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            //是否隐藏商品【1-隐藏】
            int IsHiddenGoods = parms.GetInt("IsHiddenGoods");
            List<object> resultList = new List<object>();
            var query = new RB_MiniProgram_Page_Extend() { MallBaseId = RequestParm.MallBaseId };

            var pageList = programPageModule.GetMiniprogram_Page_ListExtModule(query);
            var pageTypeList = Common.Plugin.EnumHelper.EnumToList(typeof(PageTypeEnum));
            foreach (var item in pageTypeList)
            {
                resultList.Add(new
                {
                    PageTypeName = item.Name,
                    PageTypeId = item.Id,
                    SubMenuList = pageList.Where(qitem => qitem.PageType == (PageTypeEnum)item.Id).OrderBy(qitem => qitem.PageSort)
                    .Select(qitem => new
                    {
                        qitem.PageId,
                        qitem.PageName,
                        qitem.PageUrl,
                        qitem.IsParameter,
                        qitem.ParameterValue,
                        qitem.TipText,
                        qitem.Id,
                        qitem.SelfPageName
                    })
                    .ToList()
                });
            }
            int MallBaseId = -1;
            if (UserInfo.MallBaseId > 0)
            {
                MallBaseId = UserInfo.MallBaseId;
            }
            if (MallBaseId == -1)
            {
                if (RequestParm.MallBaseId > 0)
                {
                    MallBaseId = RequestParm.MallBaseId;
                }
            }
            if (IsHiddenGoods == 0)
            {
                var categoryList = productModule.GetGoodsListModule(new Model.Extend.Product.RB_Goods_Extend()
                {
                    TenantId = RequestParm.TenantId,
                    MallBaseId = MallBaseId,
                    GoodsStatus = 1,
                });
                //新增商品选项卡
                resultList.Add(new
                {
                    PageTypeName = "商品",
                    PageTypeId = 6,
                    SubMenuList = categoryList
                });
            }
            return ApiResult.Success(data: resultList);
        }

        /// <summary>
        /// 保存小程序页面自定义标题
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniprogramPageTitle()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var pageList = JsonConvert.DeserializeObject<List<RB_MiniProgram_Page_Extend>>(parms.GetStringValue("setMsg"));
            var flag = programPageModule.SetMiniProgram_PageTitle_ByListModule(pageList);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
        #endregion

        #region 海报处理

        /// <summary>
        /// 添加修改分销海报
        /// </summary>
        /// <returns></returns>
        public ApiResult SetFenXiaoPoster()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_FenXiaoPoster_Extend>(RequestParm.msg.ToString());
            extModel.TenantId = RequestParm.TenantId;
            extModel.MallBaseId = RequestParm.MallBaseId;
            var flag = posterModule.SetFenXiaoPosterModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取分销海报
        /// </summary>
        /// <returns></returns>
        public ApiResult GetFenXiaoPoster()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_FenXiaoPoster_Extend>(RequestParm.msg.ToString());
            extModel.TenantId = RequestParm.TenantId;
            extModel.MallBaseId = RequestParm.MallBaseId;
            var result = posterModule.GetFenXiaoPosterEntityModule(extModel);
            return ApiResult.Success(data: result);
        }

        /// <summary>
        /// 添加修改商品海报
        /// </summary>
        /// <returns></returns>
        public ApiResult SetGoodPosterModule()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_GoodPoster_Extend>(RequestParm.msg.ToString());
            extModel.TenantId = RequestParm.TenantId;
            extModel.MallBaseId = RequestParm.MallBaseId;
            var flag = posterModule.SetGoodPosterModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取商品海报
        /// </summary>
        /// <returns></returns>
        public ApiResult GetGoodPoster()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_GoodPoster_Extend>(RequestParm.msg.ToString());
            extModel.TenantId = RequestParm.TenantId;
            extModel.MallBaseId = RequestParm.MallBaseId;
            var result = posterModule.GetGoodPosterEntityModule(extModel);
            return ApiResult.Success(data: result);
        }
        #endregion

        #region 用户中心配置
        /// <summary>
        /// 添加修改用户中心配置
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniUserCenterConfig()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            extModel.TenantId = RequestParm.TenantId;
            extModel.MallBaseId = RequestParm.MallBaseId;
            var flag = programModule.SetMiniUserCenterConfigModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取用户中心配置
        /// </summary>
        /// <returns></returns>
        public ApiResult GetUserCenterConfig()
        {
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_Extend>(RequestParm.msg.ToString());
            extModel.TenantId = RequestParm.TenantId;
            extModel.MallBaseId = RequestParm.MallBaseId;
            var result = programModule.GetMiniProgramModule(extModel, isGetUserCenterMenu: true);
            return ApiResult.Success(data: result);
        }

        /// <summary>
        /// 删除用户中心自定义菜单
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveMiniUserCenterMenu()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var DetailId = parms.GetStringValue("DetailId");
            var flag = programModule.DeleteMiniProgramUserCenterMenuModule(DetailIds: DetailId, MallBaseId: 0);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 根据商城Id删除用户中心菜单【恢复默认使用】
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveMiniUserCenterMenuByMallId()
        {
            var flag = programModule.DeleteMiniProgramUserCenterMenuModule(DetailIds: "", MallBaseId: RequestParm.MallBaseId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
        #endregion

        #region 插件列表

        /// <summary>
        /// 获取插件列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetPlugInList()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var extModel = new RB_PlugIn_Extend()
            {
                TenantId = RequestParm.TenantId,
                QPlugTypeStr = parms.GetStringValue("QPlugTypeStr"),
            };
            var list = plugInModule.GetPlugInListModule(extModel);
            var distinctList = list.GroupBy(qitem => new { qitem.PlugType, qitem.GroupName }).Select(qitem => new { qitem.Key.PlugType, qitem.Key.GroupName });
            List<object> resultList = new List<object>();
            foreach (var item in distinctList)
            {
                var obj = new
                {
                    item.GroupName,
                    SubList = list.Where(qitem => qitem.PlugType == item.PlugType).Select(qitem => new { qitem.Id, qitem.Name, qitem.Icon })
                };
                resultList.Add(obj);
            }
            return ApiResult.Success(data: resultList);
        }

        #endregion

        #region 轮播图

        /// <summary>
        /// 轮播图分页列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMallNavPageList()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Mall_Nav_Extend>(RequestParm.msg.ToString());
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            var list = programModule.GetMallNavPageListModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取轮播图列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMallNavList()
        {
            var query = JsonConvert.DeserializeObject<RB_Mall_Nav_Extend>(RequestParm.msg.ToString());
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            var list = programModule.GetMallNavListModule(query);
            return ApiResult.Success(data: list);
        }

        /// <summary>
        /// 新增修改轮播图
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMallNav()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Mall_Nav_Extend>(RequestParm.msg.ToString());
            extModel.Status = 0;
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            extModel.CreateDate = DateTime.Now;
            var flag = programModule.SetMallNavModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取轮播图实体
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMallNav()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var extModel = programModule.GetMallNavModule(Id);
            return ApiResult.Success(data: extModel);
        }

        /// <summary>
        /// 删除轮播图
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveMallNav()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var flag = programModule.RemoveMallNavModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
        #endregion

        #region 图片魔方管理

        /// <summary>
        /// 图片魔方分页列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMallMagicPageList()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Mall_Magic_Extend>(RequestParm.msg.ToString());
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            var list = programModule.GetMallMagicPageListModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = list;
            return ApiResult.Success(data: pageModel);
        }

        /// <summary>
        /// 获取图片魔方列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMallMagicList()
        {
            var query = JsonConvert.DeserializeObject<RB_Mall_Magic_Extend>(RequestParm.msg.ToString());
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            var list = programModule.GetMallMagicListModule(query);
            return ApiResult.Success(data: list);
        }

        /// <summary>
        /// 新增修改图片魔方
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMallMagic()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Mall_Magic_Extend>(RequestParm.msg.ToString());
            extModel.Status = 0;
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            extModel.CreateDate = DateTime.Now;
            if (extModel.MagicDataList != null && extModel.MagicDataList.Count > 0)
            {
                extModel.MagicData = Common.Plugin.JsonHelper.Serialize(extModel.MagicDataList);
            }
            var flag = programModule.SetMallMagicModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取图片魔方实体
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMallMagic()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var extModel = programModule.GetMallMagicModule(Id);
            return ApiResult.Success(data: extModel);
        }

        /// <summary>
        /// 删除图片魔方
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveMallMagic()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var flag = programModule.RemoveMallMagicModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
        #endregion

        #region 商城首页统计

        /// <summary>
        /// 首页数据统计
        /// </summary>
        /// <returns></returns>
        public ApiResult MallIndexStatistics()
        {
            var query = JsonConvert.DeserializeObject<StatisticsQuery>(RequestParm.msg.ToString());
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            //首页基础数据统计
            var basicData = programModule.MallIndexStatisticsModule(query);
            //销售情况统计
            var salesData = programModule.MallIndexSalesStatisticsModule(query);
            //商品购买力TOP排行
            var saleIncomeData = programModule.MallIndesSalesIncomeStatisticsModule(query);
            //用户购买力TOP排行
            var saleUserData = programModule.MallIndesSalesUserStatisticsModule(query);
            var obj = new
            {
                basicData,
                salesData,
                saleIncomeData,
                saleUserData
            };
            return ApiResult.Success(data: obj);
        }

        /// <summary>
        /// 下载商品购买力TOP排行
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual byte[] DownLoadSalesGoods(RequestParm request)
        {
            var query = JsonConvert.DeserializeObject<StatisticsQuery>(request.msg.ToString());
            query.MallBaseId = request.MallBaseId;
            query.TenantId = request.TenantId;
            var dataList = programModule.MallIndesSalesIncomeStatisticsModule(query);
            #region  文件下载
            List<ExcelDataSource> list = new List<ExcelDataSource>();

            ExcelDataSource header = new ExcelDataSource(30)
            {
                ExcelRows = new List<ExcelColumn>()
                {
                      new ExcelColumn(value:"序号")
                      {
                           HAlignmentEnum= HAlignmentEnum.CENTER,
                           VAlignmentEnum= VAlignmentEnum.CENTER,
                           IsBold=true
                      },
                      new ExcelColumn(value:"商品")
                      {
                           HAlignmentEnum= HAlignmentEnum.LEFT,
                           VAlignmentEnum= VAlignmentEnum.CENTER,
                           IsBold=true,
                           CellWidth=30,
                      },
                       new ExcelColumn(value:"销售额")
                      {
                           HAlignmentEnum= HAlignmentEnum.CENTER,
                           VAlignmentEnum= VAlignmentEnum.CENTER,
                           IsBold=true,
                           CellWidth=20
                      },
                      new ExcelColumn(value:"销售量")
                      {
                           HAlignmentEnum= HAlignmentEnum.CENTER,
                           VAlignmentEnum= VAlignmentEnum.CENTER,
                           IsBold=true,
                           CellWidth=20
                      }
                 }
            };
            list.Add(header);
            foreach (var item in dataList)
            {
                var ExcelDataRow = new List<ExcelColumn>
                {
                    new ExcelColumn(value: item.Num.ToString()),
                    new ExcelColumn(value: item.GoodsName),
                    new ExcelColumn(value: item.Income.ToString()),
                    new ExcelColumn(value: item.SaleCount.ToString())
                };
                ExcelDataSource dataRow = new ExcelDataSource(30)
                {
                    ExcelRows = ExcelDataRow
                };
                list.Add(dataRow);
            }
            #endregion
            var fileStream = Common.Plugin.ExcelTempLateHelper.ToExcel(list);
            return fileStream;
        }

        /// <summary>
        /// 用户购买力TOP排行
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual byte[] DownLoadSalesUser(RequestParm request)
        {
            var query = JsonConvert.DeserializeObject<StatisticsQuery>(request.msg.ToString());
            query.MallBaseId = request.MallBaseId;
            query.TenantId = request.TenantId;
            var dataList = programModule.MallIndesSalesUserStatisticsModule(query);
            #region  文件下载
            List<ExcelDataSource> list = new List<ExcelDataSource>();

            ExcelDataSource header = new ExcelDataSource(30)
            {
                ExcelRows = new List<ExcelColumn>()
                {
                      new ExcelColumn(value:"序号")
                      {
                           HAlignmentEnum= HAlignmentEnum.CENTER,
                           VAlignmentEnum= VAlignmentEnum.CENTER,
                           IsBold=true
                      },
                      new ExcelColumn(value:"用户")
                      {
                           HAlignmentEnum= HAlignmentEnum.LEFT,
                           VAlignmentEnum= VAlignmentEnum.CENTER,
                           IsBold=true,
                           CellWidth=25
                      },
                       new ExcelColumn(value:"支付金额")
                      {
                           HAlignmentEnum= HAlignmentEnum.CENTER,
                           VAlignmentEnum= VAlignmentEnum.CENTER,
                           IsBold=true,
                           CellWidth=20
                      },
                      new ExcelColumn(value:"支付件数")
                      {
                           HAlignmentEnum= HAlignmentEnum.CENTER,
                           VAlignmentEnum= VAlignmentEnum.CENTER,
                           IsBold=true,
                           CellWidth=20
                      }
                 }
            };
            list.Add(header);
            foreach (var item in dataList)
            {
                var ExcelDataRow = new List<ExcelColumn>
                {
                    new ExcelColumn(value: item.Num.ToString()),
                    new ExcelColumn(value: item.UserName),
                    new ExcelColumn(value: item.Income.ToString()),
                    new ExcelColumn(value: item.SaleCount.ToString())
                };
                ExcelDataSource dataRow = new ExcelDataSource(30)
                {
                    ExcelRows = ExcelDataRow
                };
                list.Add(dataRow);
            }
            #endregion
            var fileStream = Common.Plugin.ExcelTempLateHelper.ToExcel(list);
            return fileStream;
        }
        #endregion

        #region 分销用户统计

        /// <summary>
        /// 用户数据统计
        /// </summary>
        /// <returns></returns>
        public ApiResult MallDistributorStatistics()
        {
            var query = JsonConvert.DeserializeObject<StatisticsQuery>(RequestParm.msg.ToString());
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            //用户数据统计
            var basicData = programModule.MallDistributorStatisticsModule(query);
            return ApiResult.Success(data: basicData);
        }

        /// <summary>
        /// 每日用户统计
        /// </summary>
        /// <returns></returns>
        public ApiResult MallDistributorDayStatistics()
        {
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            var query = JsonConvert.DeserializeObject<StatisticsQuery>(RequestParm.msg.ToString());
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            //每日用户统计
            var basicData = programModule.MallDistributorDayStatisticsModule(pageModel.pageIndex, pageModel.pageSize, out long rowsCount, query);
            pageModel.count = Convert.ToInt32(rowsCount);
            pageModel.pageData = basicData;

            return ApiResult.Success(data: pageModel);
        }
        #endregion

        #region 直播配置

        /// <summary>
        /// 获取直播配置实体
        /// </summary>
        /// <returns></returns>
        public ApiResult GetLiveConfig()
        {
            var query = JsonConvert.DeserializeObject<RB_Live_Config_Extend>(RequestParm.msg.ToString());
            query.MallBaseId = RequestParm.MallBaseId;
            query.TenantId = RequestParm.TenantId;
            var extModel = programModule.GetLiveConfigModule(query);
            return ApiResult.Success(data: extModel);
        }

        /// <summary>
        /// 添加修改直播配置
        /// </summary>
        /// <returns></returns>
        public ApiResult SetLiveConfig()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Live_Config_Extend>(RequestParm.msg.ToString());
            extModel.MallBaseId = RequestParm.MallBaseId;
            extModel.TenantId = RequestParm.TenantId;
            extModel.CreateDate = DateTime.Now;
            var flag = programModule.SetLiveConfigModule(extModel);
            return flag ? ApiResult.Success(data: extModel) : ApiResult.Failed();
        }
        #endregion
    }
}