using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
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 JWT;
using Mall.Common;
using JWT.Algorithms;
using JWT.Serializers;
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;

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

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

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

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

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

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

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

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

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


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

        #region 商户信息
        [AllowAnonymous]
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        public ApiResult Login()
        {
            var query = JsonConvert.DeserializeObject<RB_Tenant_Extend>(RequestParm.msg.ToString());
            var model = new RB_Tenant_Extend();
            if (query.MallBaseId > 0)
            {
                model = TenantModule.GetTenantByMallModule(query);
            }
            else
            {
                model = TenantModule.GetTenantListModule(query).FirstOrDefault();
            }

            if (model == null)
            {
                return ApiResult.Failed("未找到此用户");
            }
            else
            {
                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("密码错误");
                    }
                }

                #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 };
                            #region JWT
                            IDateTimeProvider erpprovider = new UtcDateTimeProvider();
                            var erpnow = erpprovider.GetNow().AddMinutes(-1);
                            var erpunixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch
                            var erpsecondsSinceEpoch = Math.Round((erpnow - erpunixEpoch).TotalSeconds);
                            var erppayload = new Dictionary<string, object>
                                {
                                        {"iat",erpsecondsSinceEpoch },
                                        {"exp",erpsecondsSinceEpoch+Config.JwtExpirTime},
                                        {"userInfo",erpUserInfoToken }
                                };
                            IJwtAlgorithm erpalgorithm = new HMACSHA256Algorithm();
                            IJsonSerializer erpserializer = new JsonNetSerializer();
                            IBase64UrlEncoder erpurlEncoder = new JwtBase64UrlEncoder();
                            IJwtEncoder erpencoder = new JwtEncoder(erpalgorithm, erpserializer, erpurlEncoder);
                            string erpsecret = Config.JwtSecretKey;
                            erptoken = erpencoder.Encode(erppayload, erpsecret);
                            #endregion
                            //ERPUserInfo erpObj = new ERPUserInfo
                            //{

                            //    Domain = authorizeModel.DomainName,
                            //    emName = erpUserInfo.EmName,
                            //    EmployeeId = erpUserInfo.EmployeeId,
                            //    RB_Group_id = erpUserInfo.RB_Group_id,
                            //    RB_Branch_id = erpUserInfo.RB_Branch_id,
                            //    RB_Post_Id = erpUserInfo.RB_Post_Id,
                            //    RB_Department_Id = erpUserInfo.RB_Department_Id,
                            //    token = erptoken,
                            //    SecretKey = erpUserInfo.SecretKey,
                            //    //ImAccount = imAccount?.AccID ?? model.EmLoginMobile, //model.EmLoginMobile,
                            //    //ImToken = IMService.DefaultPassword(),
                            //};
                            //UserReidsCache.UserInfoSet(UserModuleCacheKeyConfig.ERP_Login_Info_+ erpUserInfo.EmployeeId, erpObj, Config.JwtExpirTime);
                        }
                    }

                }
                #endregion



                TokenUserInfo userInfo = new TokenUserInfo { uid = model.TenantId.ToString(), requestFrom = ApiRequestFromEnum.Web };
                #region JWT
                IDateTimeProvider provider = new UtcDateTimeProvider();
                var now = provider.GetNow().AddMinutes(-1);
                var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch
                var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
                var payload = new Dictionary<string, object>
                                {
                                        {"iat",secondsSinceEpoch },
                                        {"exp",secondsSinceEpoch+Config.JwtExpirTime},
                                        {"mall_userInfo",userInfo }
                                };
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                IJsonSerializer serializer = new JsonNetSerializer();
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
                string secret = Config.JwtSecretKey;
                string token = encoder.Encode(payload, secret);
                #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,
                    EmpId = model.EmpId,
                    erptoken = erptoken,
                    ERPEmpId = erpUserInfo.EmployeeId,
                    ERPBranchId = erpUserInfo.RB_Branch_id,
                    ERPGroupId = erpUserInfo.RB_Group_id
                };
                UserReidsCache.UserInfoSet(UserModuleCacheKeyConfig.Mall_Login_Info + model.TenantId, obj, Config.JwtExpirTime);
                return ApiResult.Success("", obj);
            }
        }

        /// <summary>
        /// 用户注册第一步
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        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]
        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]
        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>
        /// 新增修改底部导航
        /// </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 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();
        }





        //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 type = "utf-8";
        //    GetUsersHelper GetUsersHelper = new GetUsersHelper();
        //    string wenXinResult = string.Empty;
        //    JObject jo = null;
        //    result res = new result();
        //    try
        //    {
        //        wenXinResult = GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串              
        //        jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);//将字符串转换为json格式 
        //        //微信服务器验证成功 
        //        res.openid = jo["errcode"].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("");
        //}






        /// <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>();
            normalList.Add(new
            {
                key = "search",
                name = "搜索框",
                relation_id = 0,
                is_edit = 0,
                imgBg = Common.Config.GetOssFileUrl + "/Static/search-bg.png"
            });
            normalList.Add(new
            {
                key = "banner",
                name = "轮播图",
                relation_id = 0,
                is_edit = 0,
                imgBg = Common.Config.GetOssFileUrl + "/Static/banner-bg.png"
            });
            normalList.Add(new
            {
                key = "home_nav",
                name = "导航图标",
                relation_id = 0,
                is_edit = 1,
                row_num = 4,
                imgBg = Common.Config.GetOssFileUrl + "/Static/home-nav-bg.png"
            });
            normalList.Add(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"
            });
            normalList.Add(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"
            });

            normalList.Add(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"
            });
            normalList.Add(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>();
            catList.Add(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>();

            pluginList.Add(new
            {
                key = "booking",
                name = "预约",
                relation_id = 0,
                is_edit = 0,
                permission_key = "booking",
                imgBg = Common.Config.GetOssFileUrl + "/Static/yuyue-bg.png"
            });
            pluginList.Add(new
            {
                key = "pintuan",
                name = "拼团",
                relation_id = 0,
                is_edit = 0,
                permission_key = "pintuan",
                imgBg = Common.Config.GetOssFileUrl + "/Static/yuyue-bg.png"
            });
            pluginList.Add(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,
                HomeDataList = 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());
            Int32.TryParse(RequestParm.uid.ToString(), out int TenantId);
            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() { });
            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 pageList = programPageModule.GetMiniprogram_Page_ListExtModule(new RB_MiniProgram_Page_Extend() { MallBaseId = RequestParm.MallBaseId });
            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()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var flag = programModule.DeleteMiniProgramUserCenterMenuModule(DetailIds: "", MallBaseId: RequestParm.MallBaseId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
        #endregion

        #region 插件列表

        /// <summary>
        /// 获取插件列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetPlugInList()
        {
            var extModel = JsonConvert.DeserializeObject<RB_PlugIn_Extend>(RequestParm.msg.ToString());

            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>();
                ExcelDataRow.Add(new ExcelColumn(value: item.Num.ToString()));
                ExcelDataRow.Add(new ExcelColumn(value: item.GoodsName));
                ExcelDataRow.Add(new ExcelColumn(value: item.Income.ToString()));
                ExcelDataRow.Add(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>();
                ExcelDataRow.Add(new ExcelColumn(value: item.Num.ToString()));
                ExcelDataRow.Add(new ExcelColumn(value: item.UserName));
                ExcelDataRow.Add(new ExcelColumn(value: item.Income.ToString()));
                ExcelDataRow.Add(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
    }
}