using System;
using System.Collections.Generic;
using System.Linq;
using Mall.Common.API;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Mall.Common.Plugin;
using Mall.Common.Enum.User;
using Newtonsoft.Json.Linq;
using Mall.Model.Extend.Product;
using Mall.Model.Extend.MarketingCenter;
using Mall.Module.BaseSetUp;
using Mall.Common;
using Mall.CacheManager.User;
using Microsoft.AspNetCore.Authorization;

namespace Mall.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AppletUserController : BaseController
    {

        private readonly UserModule userModule = new UserModule();
        private readonly Module.MarketingCenter.CouponModule couponModule = new Module.MarketingCenter.CouponModule();
        private readonly Module.MarketingCenter.RechargeModule rechargeModule = new Module.MarketingCenter.RechargeModule();
        private readonly UserVipModule userVipModule = new UserVipModule();
        private readonly SupplierModule supplierModule = new SupplierModule();
        private readonly Module.Product.ProductModule productModule = new Module.Product.ProductModule();
        private readonly MallBaseModule MallBaseModule = new MallBaseModule();
        private readonly SmallShopsModule smallShopsModule = new SmallShopsModule();
        #region 收货地址

        /// <summary>
        /// 获取收货地址分页列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetUserShippingAddressPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Member_ShippingAddress_Extend demodel = JsonConvert.DeserializeObject<RB_Member_ShippingAddress_Extend>(req.msg.ToString());

            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = userModule.GetUserShippingAddressPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Mobile,
                x.Country,
                x.Province,
                x.City,
                x.District,
                x.DistrictAddress,
                x.Address,
                x.PostCode,
                x.Lonlat,
                x.IsDefault,
                UpdateDate = x.UpdateDate.HasValue ? x.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });

            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取收货地址列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetUserShippingAddressList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Member_ShippingAddress_Extend demodel = JsonConvert.DeserializeObject<RB_Member_ShippingAddress_Extend>(req.msg.ToString());

            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = userModule.GetUserShippingAddressList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Mobile,
                x.Country,
                x.Province,
                x.City,
                x.District,
                x.DistrictAddress,
                x.Address,
                x.PostCode,
                x.Lonlat,
                x.IsDefault,
                UpdateDate = x.UpdateDate.HasValue ? x.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            }));
        }

        /// <summary>
        /// 获取收货地址详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserShippingAddressInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int AddressId = parms.GetInt("AddressId", 0);
            if (AddressId <= 0)
            {
                return ApiResult.ParamIsNull("请传递收货地址");
            }
            var model = userModule.GetUserShippingAddressInfo(AddressId);
            if (model.TenantId != userInfo.TenantId || model.MallBaseId != userInfo.MallBaseId || model.UserId != userInfo.UserId)
            {
                return ApiResult.ParamIsNull("未查询到相关信息");
            }
            return ApiResult.Success("", new
            {
                model.Id,
                model.Name,
                model.Mobile,
                model.Country,
                model.Province,
                model.City,
                model.District,
                model.DistrictAddress,
                model.Address,
                model.PostCode,
                model.Lonlat,
                model.IsDefault
            });
        }

        /// <summary>
        /// 新增修改地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetUserShippingAddress()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Member_ShippingAddress_Extend demodel = JsonConvert.DeserializeObject<RB_Member_ShippingAddress_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入收货人");
            }
            if (string.IsNullOrEmpty(demodel.Mobile))
            {
                return ApiResult.ParamIsNull("请输入联系电话");
            }
            if ((demodel.Province ?? 0) <= 0 || (demodel.City ?? 0) <= 0 || (demodel.District ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请选择区域");
            }
            if (string.IsNullOrEmpty(demodel.Address))
            {
                return ApiResult.ParamIsNull("请输入详细地址");
            }
            demodel.IsDefault ??= 2;
            demodel.PostCode ??= "";
            demodel.Lonlat ??= "";
            demodel.Country ??= 2;
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;

            bool flag = userModule.SetUserShippingAddress(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// ERP新增用户地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult ERPSetUserShippingAddress()
        {
            var req = RequestParm;
            AppletUserInfo userInfo = null;
            JObject prams = JObject.Parse(req.msg.ToString());
            int NewUserId = prams.GetInt("NewUserId");
            if (NewUserId > 0)
            {
                userInfo = UserReidsCache.GetAppletUserLoginInfo(NewUserId);
            }
            RB_Member_ShippingAddress_Extend demodel = JsonConvert.DeserializeObject<RB_Member_ShippingAddress_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入收货人");
            }
            if (string.IsNullOrEmpty(demodel.Mobile))
            {
                return ApiResult.ParamIsNull("请输入联系电话");
            }
            if ((demodel.Province ?? 0) <= 0 || (demodel.City ?? 0) <= 0 || (demodel.District ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请选择区域");
            }
            if (string.IsNullOrEmpty(demodel.Address))
            {
                return ApiResult.ParamIsNull("请输入详细地址");
            }

            demodel.IsDefault ??= 2;
            demodel.PostCode ??= "";
            demodel.Lonlat ??= "";
            demodel.Country ??= 2;
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;

            bool flag = userModule.SetUserShippingAddress(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }


        /// <summary>
        /// 设置地址默认
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetUserShippingAddressDefault()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject prams = JObject.Parse(req.msg.ToString());
            int AddressId = prams.GetInt("AddressId", 0);
            if (AddressId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = userModule.SetUserShippingAddressDefault(AddressId, userInfo.UserId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelUserShippingAddress()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject prams = JObject.Parse(req.msg.ToString());
            int AddressId = prams.GetInt("AddressId", 0);
            if (AddressId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = userModule.DelUserShippingAddressDefault(AddressId, userInfo.UserId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }


        /// <summary>
        /// 根据地区名称获取地区列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public virtual ApiResult GetDestinationListByNames()
        {
            var request = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parm = JObject.Parse(request.msg.ToString());
            var area = parm.GetStringValue("area");
            var where = Common.Plugin.JsonHelper.DeserializeObject<string[]>(area);
            var list = userModule.GetDestinationListByNames(where);
            return ApiResult.Success(data: list.Select(qitem => new { qitem.ID, qitem.Name, qitem.CodeLevel }));
        }
        #endregion

        #region 收藏商品

        /// <summary>
        /// 获取收藏商品分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserCollectionPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(req.msg.ToString());

            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = userModule.GetUserCollectionPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.CoverImage,
                x.SellingPrice,
                x.SalesNum
            });

            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 用户收藏/取消收藏商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetUserCollectionInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = userModule.SetUserCollectionInfo(GoodsId, userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 分销中心

        /// <summary>
        /// 获取用户是否是分销商
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserDistrbutorStatus()
        {
            var userInfo = AppletUserInfo;

            var obj = userModule.GetUserDistrbutorStatus(userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 获取用户申请分销商页面信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserApplyForDistrbutorInfo()
        {
            var userInfo = AppletUserInfo;

            var obj = userModule.GetUserApplyForDistrbutorInfo(userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 用户申请成为分销商
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetUserApplyForBeDistrbutor()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Distributor_Info_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Info_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入名称");
            }
            if (string.IsNullOrEmpty(demodel.Mobile))
            {
                return ApiResult.ParamIsNull("请输入手机号码");
            }

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.TotalCommission ??= 0;
            demodel.CommissionWithdrawal ??= 0;
            demodel.GradeId ??= 0;
            demodel.AuditStatus ??= DistributorAuditStatusEnum.Auditing;
            demodel.Status = 0;
            demodel.HPGradeId ??= 0;
            demodel.FXGradeId ??= 1;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = userModule.SetUserApplyForBeDistrbutor(demodel);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }

        /// <summary>
        /// 获取分销中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserDistrbutorCenter()
        {
            var userInfo = AppletUserInfo;

            var obj = userModule.GetDistrbutorCenter(userInfo);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 获取团队成员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTeamUserInfo()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            int UserId = parms.GetInt("UserId", 0);
            var obj = userModule.GetTeamUserInfoModule(UserId);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 获取和平下线
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetHpUserReferralsAuditList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Distributor_Info_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Info_Extend>(req.msg.ToString());

            demodel.SuperiorId = userInfo.UserId;
            demodel.AuditStatus = DistributorAuditStatusEnum.Auditing;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = userModule.GetHpUserReferralsAuditList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.UserId,
                UserName = x.NickName,
                x.Photo,
                x.Name,
                x.Mobile,
                x.Source,
                SourceName = x.Source.GetEnumName(),
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 和平下线自行审核
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetHpUserReferralsAudit()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int UserId = parms.GetInt("UserId", 0);
            int Type = parms.GetInt("Type", 1);// 1 审核通过  2审核拒绝

            bool flag = userModule.SetHpUserReferralsAudit(UserId, Type, userInfo);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取用户升级条件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserDistrbutorUpgradeConditions()
        {
            var userInfo = AppletUserInfo;

            var obj = userModule.GetDistrbutorUpgradeConditions(userInfo);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 设置用户自行升级分销商等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetUserDistrbutorUpgrade()
        {
            var userInfo = AppletUserInfo;
            var req = RequestParm;
            JObject prams = JObject.Parse(req.msg.ToString());
            int GradeId = prams.GetInt("Id", 0);
            if (GradeId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = userModule.SetUserDistrbutorUpgrade(GradeId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取提现余额
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserDistrbutorWithdrawDepositBalance()
        {
            var userInfo = AppletUserInfo;

            var obj = userModule.GetDistrbutorWithdrawDepositBalance(userInfo);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 分销提现
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetUserDistrbutorWithdrawDeposit()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_Distributor_Remit_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Remit_Extend>(req.msg.ToString());
            if ((demodel.AppliedMoney ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("提现金额不能小于0");
            }
            if (demodel.WithdrawalWay == DistrbutorWithdrawWayEnum.WXZZ || demodel.WithdrawalWay == DistrbutorWithdrawWayEnum.YYKZZ || demodel.WithdrawalWay == DistrbutorWithdrawWayEnum.ZFBZZ)
            {
                if (string.IsNullOrEmpty(demodel.AccountName))
                {
                    return ApiResult.ParamIsNull("请输入账户名称");
                }
                if (string.IsNullOrEmpty(demodel.AccountNumber))
                {
                    return ApiResult.ParamIsNull("请输入账号");
                }
                if (demodel.WithdrawalWay == DistrbutorWithdrawWayEnum.YYKZZ)
                {
                    if (string.IsNullOrEmpty(demodel.BankName))
                    {
                        return ApiResult.ParamIsNull("请输入银行名称");
                    }
                }
            }

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.AuditStatus = DistributorRemitAuditStatusEnum.Auditing;
            demodel.CreateDate = DateTime.Now;
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNum = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            string msg = userModule.SetDistrbutorWithdrawDeposit(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取分销佣金页面信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserDistrbutorCommissionInfo()
        {
            var userInfo = AppletUserInfo;

            var obj = userModule.GetDistrbutorCommissionInfo(userInfo);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 获取用户提现明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserDistrbutorRemitPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Distributor_Remit_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Remit_Extend>(req.msg.ToString());

            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = userModule.GetDistributorRemitPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.OrderNum,
                x.WithdrawalWay,
                WithdrawalWayName = x.WithdrawalWay.GetEnumName(),
                x.AccountName,
                x.AccountNumber,
                x.BankName,
                x.AppliedMoney,
                x.Fee,
                x.RemitMoney,
                x.AuditRemark,
                x.RemitRemark,
                x.RejectRemark,
                x.AuditStatus,
                AuditStatusName = x.AuditStatus.GetEnumName(),
                x.TenantId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                AuditDate = x.AuditDate.HasValue ? x.AuditDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                RemitDate = x.RemitDate.HasValue ? x.RemitDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                RejectDate = x.RejectDate.HasValue ? x.RejectDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取我的团队里 自定义信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserMyTeamCustomInfo()
        {
            var userInfo = AppletUserInfo;

            var obj = userModule.GetUserMyTeamCustomInfo(userInfo);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 获取分销商团队
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserMyTeamPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Distributor_Info_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Info_Extend>(req.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            pageModel.pageData = userModule.GetUserMyTeamPageList(pageModel.pageIndex, pageModel.pageSize, out long count, demodel);
            pageModel.count = Convert.ToInt32(count);

            return ApiResult.Success("", pageModel);
        }


        /// <summary>
        /// 获取我的团队里粉象返佣标题
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GerUserMyTeamTitelListForFX()
        {
            var userInfo = AppletUserInfo;
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            //是否直属
            int IsDirect = parms.GetInt("IsDirect", 0);
            var obj = userModule.GerUserMyTeamTitelListForFX(userInfo, IsDirect: IsDirect);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 获取我的团队  粉象返佣列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetUserMyTeamPageListForFX()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Distributor_Info_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Info_Extend>(req.msg.ToString());
            JObject prams = JObject.Parse(req.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.IsDirect = prams.GetInt("IsDirect", 0);
            int NewUserId = 0;
            //HK 2020-08-27新增
            JObject parms = JObject.Parse(req.msg.ToString());
            if (parms.GetInt("NewUserId") > 0)
            {
                demodel.UserId = parms.GetInt("NewUserId");
                NewUserId = parms.GetInt("NewUserId");
            }
            var list = userModule.GetUserMyTeamPageListForFX(pageModel.pageIndex, pageModel.pageSize, out long count, demodel, NewUserId: NewUserId);


            pageModel.count = Convert.ToInt32(count);
            pageModel.pageData = list;
            return ApiResult.Success("", pageModel);
        }

        /// <summary>
        /// 获取粉象等级升级条件
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserDistrbutorUpgradeConditionsForFX()
        {
            var userInfo = AppletUserInfo;

            var obj = userModule.GetUserDistrbutorUpgradeConditionsForFX(userInfo);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 设置自行升级粉象等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetUserDistrbutorUpgradeForFX()
        {
            var userInfo = AppletUserInfo;
            var req = RequestParm;
            JObject prams = JObject.Parse(req.msg.ToString());
            int GradeId = prams.GetInt("GradeId", 0);
            if (GradeId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = userModule.SetUserDistrbutorUpgradeForFX(GradeId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取用户vip分销返佣订单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserVipCommissionOrdersPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_VipBuy_Commission_Extend demodel = JsonConvert.DeserializeObject<RB_VipBuy_Commission_Extend>(req.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            var list = userModule.GetUserVipCommissionOrdersPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.OrderId,
                x.OrderNo,
                x.Grade,
                x.GradeName,
                x.GradeDescription,
                x.UserId,
                x.UserName,
                x.Photo,
                x.Commission,
                x.Remark,
                x.Type,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取用户vip购买 权益介绍
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserVipBuyRecommend()
        {
            var userInfo = AppletUserInfo;
            var req = RequestParm;
            JObject prams = JObject.Parse(req.msg.ToString());
            int GradeId = prams.GetInt("GradeId", 0);
            if (GradeId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var robj = userModule.GetUserVipBuyRecommend(GradeId, userInfo);
            return ApiResult.Success("", robj);
        }

        /// <summary>
        /// 获取我的用户层级关系图
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMyUserHierarchicalRelationList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int UserId = parms.GetInt("UserId", 0);
            if (UserId <= 0) {
                return ApiResult.ParamIsNull("请传递用户id");
            }

            return userModule.GetMyUserHierarchicalRelationList(UserId, userInfo.UserId);
        }
        #endregion

        #region 会员中心

        /// <summary>
        /// 获取用户会员中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserMemberCenter()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;

            var Robj = userModule.GetUserMemberCenterInfo(userInfo);
            return ApiResult.Success("", Robj);
        }

        /// <summary>
        /// 用户升级会员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetUserUpGradeMemberInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GradeId = parms.GetInt("GradeId", 0);
            if (GradeId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            string msg = userModule.GetUserMemberCenterInfo(GradeId, userInfo);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 我的足迹

        /// <summary>
        /// 获取我的足迹分页类别
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserFootMarkPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Member_Footmark_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Footmark_Extend>(req.msg.ToString());

            demodel.UserId = userInfo.UserId;
            //HK 2020-08-27新增
            JObject parms = JObject.Parse(req.msg.ToString());
            if (parms.GetInt("NewUserId") > 0)
            {
                demodel.UserId = parms.GetInt("NewUserId");
            }
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = userModule.GetUserFootMarkPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.GoodsId,
                x.GoodsName,
                x.GoodsImgPath,
                x.Price,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : "",
                x.GoodsClassify,
            });

            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 新增足迹
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetUserFootMarkInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            if (GoodsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = userModule.SetUserFootMarkInfo(GoodsId, userInfo);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除足迹
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelUserFootMarkInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int FootMarkId = parms.GetInt("FootMarkId", 0);
            if (FootMarkId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = userModule.DelUserFootMarkInfo(FootMarkId, userInfo);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 个人中心

        /// <summary>
        /// 获取用户中心统计
        /// </summary>
        /// <returns></returns>
        //[HttpPost]
        //public ApiResult GetAppletUserCenterStatistics()
        //{
        //    var userInfo = AppletUserInfo;
        //    return userModule.GetAppletUserCenterStatistics(userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
        //}

        /// <summary>
        /// 获取用户类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletUserPageType() {
            var userInfo = AppletUserInfo;

            return userModule.GetAppletUserPageType(userInfo);
        }
        #endregion        

        #region 优惠券

        /// <summary>
        /// 领劵中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAllCouponPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_DiscountCoupon_Extend demodel = JsonConvert.DeserializeObject<RB_DiscountCoupon_Extend>(req.msg.ToString());
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.SmallShopId = userInfo.UserSmallShopId;
            var list = couponModule.GetAllCouponList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Name,
                x.Describe,
                x.MinConsumePrice,
                x.MaxDiscountsPrice,
                x.DiscountsPrice,
                x.CouponType,
                CouponId = x.ID,
                x.IndateDay,
                x.IndateType,
                StartDate = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                EndDate = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                IsReceive = x.MemberNum > 0 ? 1 : 0,
                UseTypeStr = ((int)x.UseType == 3 || (int)x.UseType == 4) ? x.UseType.GetEnumName() : (x.ProductList != null && x.ProductList.Any() ? string.Join("、", x.ProductList.Select(x => x.Relevance)) : ""),
                x.UseType,
                x.ProductList
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 领取优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GrantCoupon()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Member_DiscountCoupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;
            if (query == null)
            {
                return ApiResult.Failed("请传入卡券信息");
            }
            else
            {
                var oldLogisticsModel = couponModule.GetDiscountCouponList(new RB_DiscountCoupon_Extend { TenantId = query.TenantId, MallBaseId = query.MallBaseId, ID = query.CouponId }).FirstOrDefault();
                var allMemberInfo = userModule.GetMemberUserInfo(userInfo.UserId);

                if (oldLogisticsModel == null || oldLogisticsModel.ID == 0)
                {
                    return ApiResult.Failed("优惠券信息不存在，请核实后再操作");
                }
                if (allMemberInfo.SmallShopId == 0)
                {
                    if (oldLogisticsModel.SmallShopId > 0)
                    {
                        return ApiResult.Failed("您不属于当前店铺");
                    }
                }
                else
                {
                    if (oldLogisticsModel.SmallShopId > 0 && oldLogisticsModel.SmallShopId != allMemberInfo.SmallShopId)
                    {
                        return ApiResult.Failed("领取优惠券不属于当前店铺");
                    }
                    if (allMemberInfo.SmallShopId > 0 && oldLogisticsModel.SmallShopId == 0 && oldLogisticsModel.IsZanYangUse == 1)
                    {
                        return ApiResult.Failed("领取优惠券不属于当前店铺");
                    }
                }


                if (oldLogisticsModel.TotalNum != -1)//判断优惠券剩余数量是够足够
                {
                    if (oldLogisticsModel.TotalNum < 1)
                    {
                        return ApiResult.Failed("优惠券已领完");
                    }
                }
                //判断优惠券是否已领取
                var receiveList = couponModule.GetMemberDiscountCouponList(query);
                if (receiveList != null && receiveList.Any())
                {
                    return ApiResult.Failed("您已领取优惠券");
                }

                if (oldLogisticsModel.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.TimeHorizon)
                {
                    if (oldLogisticsModel.EndDate.Value < System.DateTime.Now)
                    {
                        return ApiResult.Failed("优惠券时间已过期");
                    }
                }

                //判断优惠券是否有等级限制
                if (oldLogisticsModel.OnlyMember == 1)
                {
                    if (!string.IsNullOrWhiteSpace(oldLogisticsModel.MemberLevel))
                    {
                        string[] allLevel = oldLogisticsModel.MemberLevel.Split(',');
                        if (allLevel.Where(x => x == allMemberInfo.MemberGrade.ToString()).Count() == 0)
                        {
                            return ApiResult.Failed("会员等级不符合");
                        }
                    }
                }


                RB_Member_DiscountCoupon_Extend memberCoupon = new RB_Member_DiscountCoupon_Extend();
                memberCoupon.Id = 0;
                memberCoupon.UserId = userInfo.UserId;
                memberCoupon.Description = oldLogisticsModel.Describe;
                memberCoupon.CreateDate = System.DateTime.Now;
                memberCoupon.TenantId = userInfo.TenantId;
                memberCoupon.MallBaseId = userInfo.MallBaseId;
                memberCoupon.Remarks = "";
                memberCoupon.CouponId = oldLogisticsModel.ID;
                memberCoupon.Name = oldLogisticsModel.Name;
                memberCoupon.CouponType = oldLogisticsModel.CouponType;
                memberCoupon.MinConsumePrice = oldLogisticsModel.MinConsumePrice;
                memberCoupon.MaxDiscountsPrice = oldLogisticsModel.MaxDiscountsPrice;
                memberCoupon.DiscountsPrice = oldLogisticsModel.DiscountsPrice;
                memberCoupon.UseType = oldLogisticsModel.UseType;
                if (oldLogisticsModel.IndateType == Common.Enum.MarketingCenter.IndateTypeEnum.DayHorizon)
                {
                    memberCoupon.StartDate = System.DateTime.Now;
                    LogHelper.WriteInfo(userInfo.Name + "优惠券领取时间:" + memberCoupon.StartDate);
                    memberCoupon.EndDate = memberCoupon.StartDate.Value.AddDays(oldLogisticsModel.IndateDay);
                }
                else
                {
                    memberCoupon.StartDate = oldLogisticsModel.StartDate;
                    memberCoupon.EndDate = oldLogisticsModel.EndDate;
                }
                var memberList = new List<RB_Member_DiscountCoupon_Extend>();
                memberList.Add(memberCoupon);
                bool result = couponModule.GrantCoupon(memberList, oldLogisticsModel);
                if (result)
                {
                    return ApiResult.Success("优惠券信息领取成功");
                }
                else
                {
                    return ApiResult.Failed("优惠券信息领取成功");
                }
            }
        }


        /// <summary>
        /// 我的优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberCouponPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_DiscountCoupon_Extend demodel = JsonConvert.DeserializeObject<RB_DiscountCoupon_Extend>(req.msg.ToString());
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = couponModule.GetMemberDisCouponList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Name,
                x.Describe,
                x.MinConsumePrice,
                x.MaxDiscountsPrice,
                x.DiscountsPrice,
                x.CouponType,
                x.ID,
                x.MemberCouponId,
                StartDate = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                EndDate = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:ss:mm") : "",
                UseTypeStr = ((int)x.UseType == 3 || (int)x.UseType == 4) ? x.UseType.GetEnumName() : (x.ProductList != null && x.ProductList.Any() ? string.Join("、", x.ProductList.Select(x => x.Relevance)) : ""),
                x.UseType,
                x.ProductList
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 分享领取优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult ShareCoupon()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_DiscountCoupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;
            RB_DiscountCoupon_Extend resultModel = new RB_DiscountCoupon_Extend();
            if (query.TriggerType == 2)
            {

                query.TriggerType = 4;
                resultModel = couponModule.AutoCoupon(query);
                if (resultModel == null || resultModel.ID == 0)
                {
                    query.TriggerType = 2;
                    resultModel = couponModule.AutoCoupon(query);
                }
            }
            else
            {
                resultModel = couponModule.AutoCoupon(query);
            }
            if (resultModel != null && resultModel.ID > 0)
            {
                return ApiResult.CouponSuccess(ResultCode.Success, 1, "", resultModel.Name);
            }
            else
            {
                return ApiResult.CouponFailed(ResultCode.Fail, 1, "", "");
            }

            //RB_DiscountCoupon_Extend resultModel = couponModule.AutoCoupon(query);
            //if (resultModel != null && resultModel.ID > 0)
            //{
            //    return ApiResult.CouponSuccess(ResultCode.Success, "", resultModel.Name);
            //}
            //else
            //{
            //    return ApiResult.CouponFailed(ResultCode.Fail, "", "");
            //}
        }


        #endregion

        #region 个人中心- 积分明细
        /// <summary>
        ///  个人中心- 积分明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberIntegralPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Member_Integral_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Integral_Extend>(req.msg.ToString());
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = userModule.GetMemberIntegralPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Remarks,
                x.Description,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.Integral,
                x.Type
            });
            return ApiResult.Success("", pagelist);
        }
        #endregion

        #region 余额明细
        /// <summary>
        ///  个人中心- 积分明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberBalancePageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject prams = JObject.Parse(req.msg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            var createDateStr = prams.GetStringValue("CreateDate") + "-01";
            RB_Member_Balance_Extend demodel = new RB_Member_Balance_Extend();
            if (!string.IsNullOrWhiteSpace(createDateStr))
            {
                try
                {
                    demodel.CreateDate = Convert.ToDateTime(createDateStr);
                }
                catch
                {
                    demodel.CreateDate = DateTime.Now;
                }
            }
            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = userModule.GetMemberBalancePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Remarks,
                x.Description,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.Balance,
                x.Type
            });
            return ApiResult.Success("", pagelist);
        }
        #endregion

        #region 获取小程序码

        /// <summary>
        /// 获取微信小程序码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeiXinQRCodeForApplet()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            string Path = parms.GetStringValue("Path");//路径
            int With = parms.GetInt("With", 430);//大小
            if (string.IsNullOrEmpty(Path))
            {
                return ApiResult.ParamIsNull("请传递路径");
            }

            string base64Img = userModule.GetWeiXinQRCode(Path, With, userInfo.MallBaseId);
            return ApiResult.Success("", base64Img);
        }

        /// <summary>
        /// 获取微信小程序码(微店)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeiXinQRCodeForAppletSmallShops()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            string Path = parms.GetStringValue("Path");//路径
            int With = parms.GetInt("With", 430);//大小
            if (string.IsNullOrEmpty(Path))
            {
                return ApiResult.ParamIsNull("请传递路径");
            }

            string base64Img = userModule.GetWeiXinQRCodeForSmallShops(Path, With, userInfo.MallBaseId, userInfo.UserId);
            return ApiResult.Success("", base64Img);
        }

        #endregion

        #region 获取分销海报

        /// <summary>
        /// 获取分销海报
        /// </summary>
        /// <returns></returns>
        public ApiResult GetFenXiaoPoster()
        {
            var userInfo = AppletUserInfo;
            JObject jobj = JObject.Parse(RequestParm.msg.ToString());
            var extModel = JsonConvert.DeserializeObject<RB_MiniProgram_FenXiaoPoster_Extend>(RequestParm.msg.ToString());
            extModel.TenantId = userInfo.TenantId;
            extModel.MallBaseId = userInfo.MallBaseId;
            extModel.IsOpenSchool = jobj.GetInt("IsOpenSchool", 0);
            var result = userModule.GetFenXiaoPosterEntityModule(extModel);
            return ApiResult.Success(data: result);
        }

        #endregion

        #region 个人中心余额/积分/优惠券气泡
        /// <summary>
        ///  个人中心- 积分明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserCenter()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;

            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(req.msg.ToString());
            demodel.Id = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;

            //获取用户的基本信息
            var userModel = userModule.GetMemberUserEntityModule(demodel);

            if (userModel == null)
            {
                return ApiResult.Failed("用户信息不存在");

            }

            //获取用户的优惠券信息
            var couponList = couponModule.GetMemberDiscountCouponList(new RB_Member_DiscountCoupon_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UseState = 0, UserId = userModel.Id });
            var result = new
            {
                Balance = userModel.Balance ?? 0,//余额
                Integral = userModel.Integral ?? 0,//积分
                couponCount = (couponList == null || !couponList.Any()) ? 0 : couponList.Count(),//优惠券
                couponCardCount = 0//卡券
            };
            return ApiResult.Success("");
        }
        #endregion

        #region 充值
        /// <summary>
        ///  个人中心- 用户充值设置与规则
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserRechargeSettings()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;

            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(req.msg.ToString());
            demodel.Id = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;

            //获取充值规则
            var rechargeRules = rechargeModule.GetRechargeRulesList(new RB_Recharge_Rules_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            //获取充值规则
            var rechargeSettings = rechargeModule.GetRechargeSettingsList(new Model.Entity.MarketingCenter.RB_Recharge_Settings { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
            return ApiResult.Success("", new { rechargeRules, rechargeSettings });
        }
        #endregion


        #region vip购买

        /// <summary>
        ///  个人中心- 用户充值设置与规则
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserVipSettings()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;

            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(req.msg.ToString());
            demodel.Id = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;

            //获取自定义购买vip页面设置
            var fxGradeCustom = userVipModule.GetGradeCustomList(new RB_Distributor_FXGradeCustom_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();
            //获取购买vip列表
            var fxGrade = userModule.GetFXDistributorGradeList(new RB_Distributor_FXGrade_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, IsCanBuy = 1, IsGuest = 3 });
            return ApiResult.Success("", new { fxGradeCustom, fxGrade });
        }


        /// <summary>
        ///  个人中心- vip购买记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetVipBuyPageList()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Vip_Buy_Extend demodel = JsonConvert.DeserializeObject<RB_Vip_Buy_Extend>(parms.msg.ToString());
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.PayState = 1;
            var list = userVipModule.GetVipBuyPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.OrderNo,
                x.UserName,
                x.Money,
                ExpiryDateStr = x.ExpiryDate.HasValue ? x.ExpiryDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.GradeName,
                x.PayState,
                x.PayWay,
                PayTimeStr = x.PayTime.HasValue ? x.PayTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.Remark
            });
            return ApiResult.Success("", pagelist);
        }

        #endregion

        #region 个人中心供应商
        /// <summary>
        /// 获取用户会员中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserMemberSupplierCenter()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            var orderIntroduction = userModule.GetOrderIntroductionList(new RB_Goods_OrderIntroduction_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId });
            var DistributorBillList = userModule.GetDistributorBillList(new RB_Distributor_Bill_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId, SelectBillState = -1 });
            var SupplierList = supplierModule.GetList(new RB_Supplier_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, Introducer = userInfo.UserId });//我的供应商
            int SupplierCount = 0;
            List<RB_Goods_Extend> GoodsList = new List<RB_Goods_Extend>();
            string supplierIds = string.Empty;
            if (SupplierList != null && SupplierList.Any())
            {
                SupplierCount = SupplierList.Count();
                supplierIds = string.Join(",", SupplierList.Select(x => x.ID));
                GoodsList = productModule.GetGoodsList(new RB_Goods_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, SupplierIds = supplierIds });
            }
            var obj = new
            {
                TotalDistributorBill = (DistributorBillList != null && DistributorBillList.Any()) ? DistributorBillList.Sum(x => (x.Money ?? 0)) : 0,//已打款金额
                TotalOrderIntroduction = (orderIntroduction != null && orderIntroduction.Any()) ? orderIntroduction.Sum(x => x.Commission ?? 0) : 0, //返佣总金额
                SettlementIntroduction = (orderIntroduction != null && orderIntroduction.Any()) ? orderIntroduction.Where(x => x.CommissionState == 2).Sum(x => x.Commission ?? 0) : 0,    //已结算佣金
                NoSettlementIntroduction = (orderIntroduction != null && orderIntroduction.Any()) ? orderIntroduction.Where(x => x.CommissionState == 1).Sum(x => x.Commission ?? 0) : 0,  //未结算佣金
                SupplierCount,//我的供应商
                supplierIds,
                GoodsCount = (GoodsList != null && GoodsList.Any()) ? GoodsList.Count() : 0
            };
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 获取用户会员中心-我的供应商
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserMemberSupplier()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;

            var SupplierList = supplierModule.GetList(new RB_Supplier_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, Introducer = userInfo.UserId });//我的供应商

            var obj = SupplierList.Select(x => new { x.ID, x.Name, x.Mobile, SupplierCommissionList = x.SupplierCommissionList.Select(y => new { y.CommissionRate, y.CommissionType }) });
            return ApiResult.Success("", obj);
        }


        /// <summary>
        /// 获取用户会员中心-我的产品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAppletGoodsPageList()
        {
            var requestMsg = RequestParm;
            var userInfo = AppletUserInfo;
            //   var parms = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());

            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(requestMsg.msg.ToString());
            RB_Goods_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_Extend>(requestMsg.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            List<RB_Goods_Extend> list = new List<RB_Goods_Extend>();
            if (!string.IsNullOrWhiteSpace(demodel.SupplierIds))
            {
                list = productModule.GetAppletGoodsPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
                //更加商品id获取规格信息
                string goodsIds = string.Join(",", list.Where(x => x.IsCustomSpecification == 1).Select(x => x.Id));
                var SpecificationList = productModule.GetSpecificationList(new RB_Goods_Specification_Extend() { GoodsIds = goodsIds, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                var SpecificationPriceList = productModule.GetSpecificationPriceList(new RB_Goods_SpecificationPrice_Extend() { GoodsIds = goodsIds, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                var SpecificationValueList = productModule.GetSpecificationValueList(new RB_Goods_SpecificationValue_Extend() { GoodsIds = goodsIds, TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });
                foreach (var item in list)
                {

                    #region 组装价格
                    List<object> priceList = new List<object>();
                    if (item.IsCustomSpecification == 1)
                    {
                        item.SpecificationPriceList = SpecificationPriceList.Where(x => x.GoodsId == item.Id).ToList();
                        item.SpecificationList = SpecificationList.Where(x => x.GoodsId == item.Id).ToList();
                        if (item.SpecificationList.Any())
                        {
                            var svlist = SpecificationValueList.Where(x => x.GoodsId == item.Id).ToList();
                            foreach (var itemSpecificationValue in svlist)
                            {
                                itemSpecificationValue.ImagePath = itemSpecificationValue.Image;
                            }
                            foreach (var itemSpecification in item.SpecificationList)
                            {
                                itemSpecification.SpecificationValueList = svlist.Where(x => x.SpecificationId == itemSpecification.Id).ToList();
                            }
                        }
                        if (item.SpecificationPriceList.Any() && item.SpecificationList.Any())
                        {
                            List<RB_Goods_Specification_Extend> SpecificationListToPrice = new List<RB_Goods_Specification_Extend>();
                            List<RB_Goods_SpecificationValue_Extend> SpecificationValueListToPrice = new List<RB_Goods_SpecificationValue_Extend>();
                            bool IsHaveSellingPriceZero = false;
                            if (item.SpecificationPriceList.Where(x => x.SellingPrice > 0).Count() != item.SpecificationPriceList.Count())
                            {
                                //有数量为0的
                                IsHaveSellingPriceZero = true;
                            }
                            foreach (var itemSpecificationPrice in item.SpecificationPriceList.Where(x => x.SellingPrice > 0))
                            {
                                var ssarr = itemSpecificationPrice.SpecificationSort.Split(':');
                                int Sort = Convert.ToInt32(ssarr[0]);
                                string pic_url = item.SpecificationList[0].SpecificationValueList.Where(x => x.Sort == Sort).FirstOrDefault()?.ImagePath;
                                List<object> attr_list = new List<object>();
                                for (int i = 0; i < ssarr.Length; i++)
                                {
                                    var smodel = item.SpecificationList[i];
                                    if (IsHaveSellingPriceZero && !SpecificationListToPrice.Where(x => x.Id == smodel.Id).Any())
                                    {
                                        SpecificationListToPrice.Add(smodel);
                                    }
                                    var svmodel = smodel.SpecificationValueList.Where(x => x.Sort == Convert.ToInt32(ssarr[i])).FirstOrDefault();
                                    if (IsHaveSellingPriceZero && !SpecificationValueListToPrice.Where(x => x.Id == svmodel.Id).Any())
                                    {
                                        SpecificationValueListToPrice.Add(svmodel);
                                    }
                                    attr_list.Add(new
                                    {
                                        attr_group_name = smodel.Name,
                                        attr_group_id = smodel.Sort,
                                        attr_id = svmodel.Id,
                                        attr_name = svmodel.Name
                                    });
                                }

                                priceList.Add(new
                                {
                                    id = itemSpecificationPrice.Id,
                                    goods_id = itemSpecificationPrice.Id,
                                    sign_id = itemSpecificationPrice.SpecificationSort,
                                    stock = itemSpecificationPrice.InventoryNum,
                                    price = itemSpecificationPrice.SellingPrice,
                                    no = itemSpecificationPrice.GoodsNumbers,
                                    weight = itemSpecificationPrice.GoodsWeight,
                                    costPrice = itemSpecificationPrice.CostMoney,
                                    pic_url,
                                    is_delete = itemSpecificationPrice.Status,
                                    attr_list
                                });
                            }
                            //当只有一组规格项目时  
                            if (IsHaveSellingPriceZero && SpecificationListToPrice.Any() && item.SpecificationList.Count() == 1)
                            {
                                foreach (var itemSpecificationList in SpecificationListToPrice)
                                {
                                    itemSpecificationList.SpecificationValueList = SpecificationValueListToPrice.Where(x => x.SpecificationId == itemSpecificationList.Id).OrderBy(x => x.Sort).ToList();
                                }
                                SpecificationListToPrice = SpecificationListToPrice.Where(x => x.SpecificationValueList.Any()).ToList();
                                //有价格小于等于0的   在前端展示时   需屏蔽掉
                                item.SpecificationList = SpecificationListToPrice;
                            }
                        }
                    }
                    else
                    {
                        decimal price_member = item.SellingPrice ?? 0;//未设会员价格的话  就为销售价格
                        priceList.Add(new
                        {
                            id = 0,
                            goods_id = item.Id,
                            sign_id = "",
                            stock = item.InventoryNum,
                            price = item.SellingPrice ?? 0,
                            costPrice = item.CostPrice,
                            no = item.GoodsNumbers,
                            weight = item.GoodsWeight,
                            pic_url = "",
                            is_delete = 0,
                            attr_list = new List<object>(){ new
                    {
                        attr_group_name = "规格",
                        attr_group_id = 0,
                        attr_id = 0,
                        attr_name = item.DefaultSpecificationName
                    } },
                        });
                    }
                    item.SupplierSpecificationList = priceList;
                    #endregion
                }

                pagelist.count = Convert.ToInt32(count);

            }
            else
            {
                pagelist.count = 0;
            }
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Sort,
                x.CoverImage,
                x.VideoAddress,
                x.SellingPrice,
                x.SalesNum,
                x.IsQuickBuy,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.SupplierSpecificationList
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 我的账单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSupplierDistributorBill()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Distributor_Bill_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Bill_Extend>(req.msg.ToString());

            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = userModule.GetRecommendOrdersBillPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Money,
                x.FinanceId,
                x.Periods,
                x.BillState,
                x.SupplierName
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 供应商-我的订单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetUserDistributionOrdersPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Goods_OrderIntroduction_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderIntroduction_Extend>(req.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            List<RB_Member_User_Extend> memberList = new List<RB_Member_User_Extend>();
            var list = userModule.GetOrderIntroductionPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);

            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                DetailList = x.OrderDetailList.Select(y => new
                {
                    y.Id,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                    y.ProductCode,
                    y.Final_Price,
                    y.Number
                }),
                x.UserId,

                x.UserName,
                x.Photo,
                x.Mobile,
                x.Remark,
                x.Commission,
                x.CommissionState,
                StatusName = x.DistrbutionOrderSelectStatus == 1 ? "待付款" : x.DistrbutionOrderSelectStatus == 5 ? "已完成" : "已付款",
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 我的账单详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetOrderBilldetailPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Goods_OrderIntroduction_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderIntroduction_Extend>(req.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = userModule.GetOrderBilldetailPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                DetailList = x.OrderDetailList.Select(y => new
                {
                    y.Id,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                    y.ProductCode,
                    y.Final_Price,
                    y.Number
                }),
                x.UserId,
                x.UserName,
                x.Photo,
                x.Mobile,
                x.Remark,
                x.Commission,
                x.CommissionState,
                StatusName = x.DistrbutionOrderSelectStatus == 1 ? "待付款" : x.DistrbutionOrderSelectStatus == 5 ? "已完成" : "已付款",
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }
        #endregion

        #region 微店

        /// <summary>
        /// 获取微信基础设置信息
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMicroShopBasics()
        {

            var req = RequestParm;
            var userInfo = AppletUserInfo;
            var microShopBasics = MallBaseModule.GetMicroShopBasics(new Model.Entity.BaseSetUp.RB_MicroShop_Basics { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });


            return ApiResult.Success("", microShopBasics);
        }

        /// <summary>
        /// 获取微店申请记录
        /// </summary>
        /// <returns></returns>
        public ApiResult GetSmallShopsApplyInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            var oldModel = userModule.GetSmallShopsInfoList(new RB_SmallShops_Info_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId }).OrderByDescending(x => x.CreateDate).FirstOrDefault();
            if (oldModel == null)
            {
                oldModel = new RB_SmallShops_Info_Extend();
            }
            return ApiResult.Success("", oldModel);
        }


        /// <summary>
        /// 申请微店
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult ApplySmallShopsInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_SmallShops_Info_Extend demodel = JsonConvert.DeserializeObject<RB_SmallShops_Info_Extend>(req.msg.ToString());

            var memberModel = userModule.GetMemberUserInfo(userInfo.UserId);
            if (memberModel == null)
            {
                return ApiResult.Failed("用户信息不存在");
            }

            //if (memberModel.SmallShopId > 0)
            //{
            //    return ApiResult.Failed("当前不满足申请资格，请联系客服");
            //}
            //判断是否满足当前申请条件
            var microShopBasics = MallBaseModule.GetMicroShopBasicsList(new Model.Entity.BaseSetUp.RB_MicroShop_Basics { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId }).FirstOrDefault();

            if (microShopBasics == null)
            {
                return ApiResult.Failed("微店申请暂未开启");
            }
            if (microShopBasics.IsOpen != 2)
            {
                return ApiResult.Failed("微店申请暂未开启");
            }
            if (microShopBasics.ApplyCondition > 0)
            {
                var distributorInfoModel = userModule.GetDistributorInfoList(new RB_Distributor_Info_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId }).FirstOrDefault();
                if (microShopBasics.ApplyMemberLevel > 0 && microShopBasics.ApplyCondition == 1)
                {
                    var list = userModule.GetDistributorGradeDropdownList(new RB_Distributor_Grade_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

                    var nowLevel = list.Where(x => x.Id == microShopBasics.ApplyMemberLevel).FirstOrDefault();//申请等级的最低id
                    var memberLevel = list.Where(x => x.Id == distributorInfoModel.GradeId).FirstOrDefault();//会员当前的等级
                    if ((memberLevel.Grade ?? 0) < (nowLevel.Grade ?? 0))
                    {
                        return ApiResult.Failed("当前等级不满足");
                    }
                }
                else if (microShopBasics.ApplyMemberLevel > 0 && microShopBasics.ApplyCondition == 2)
                {
                    var list = userModule.GetFXDistributorGradeList(new RB_Distributor_FXGrade_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId });

                    var nowLevel = list.Where(x => x.Id == microShopBasics.ApplyMemberLevel).FirstOrDefault();//申请等级的最低id
                    var memberLevel = list.Where(x => x.Id == distributorInfoModel.FXGradeId).FirstOrDefault();//会员当前的等级
                    if ((memberLevel.Grade ?? 0) < (nowLevel.Grade ?? 0))
                    {
                        return ApiResult.Failed("当前等级不满足");
                    }
                }
            }

            //判断是否已经申请过，已申请并拒绝不能再次申请
            var oldList = userModule.GetSmallShopsInfoList(new RB_SmallShops_Info_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId }).OrderByDescending(x => x.CreateDate).FirstOrDefault();
            if (oldList != null)
            {
                if (oldList.AuditStatus == DistributorAuditStatusEnum.Reject)
                {
                    return ApiResult.Failed("您之前的申请已被拒绝，不能再次申请");
                }
                else if (oldList.AuditStatus == DistributorAuditStatusEnum.Audited)
                {
                    return ApiResult.Failed("您的申请已通过，请勿重复申请");
                }
                else if (oldList.AuditStatus == DistributorAuditStatusEnum.Auditing)
                {
                    return ApiResult.Failed("您已申请,请等待审核");
                }
            }

            if (string.IsNullOrEmpty(demodel.Name))
            {
                demodel.Name = userInfo.Name;
            }
            if (string.IsNullOrEmpty(demodel.Logo))
            {
                demodel.Logo = userInfo.Photo;
            }
            demodel.UserId = userInfo.UserId;
            demodel.GradeId = 0;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.TotalCommission = 0;
            demodel.Commission = 0;
            demodel.UpPrice = 0;
            demodel.PriceType = 0;
            demodel.Status = 0;
            demodel.AuditStatus = microShopBasics.IsExamine == 1 ? DistributorAuditStatusEnum.Audited : DistributorAuditStatusEnum.Auditing;
            if (microShopBasics.IsExamine == 1 && memberModel.SmallShopId > 0)
            {
                memberModel.Remark += "原店铺ID:" + memberModel.SmallShopId;
            }
            bool flag = userModule.ApplySmallShopsInfo(demodel, memberModel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 更新微店信息
        /// </summary>
        /// <returns></returns>
        public ApiResult UpdateShopsInfo()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_SmallShops_Info_Extend demodel = JsonConvert.DeserializeObject<RB_SmallShops_Info_Extend>(req.msg.ToString());
            var oldList = userModule.GetSmallShopsInfoList(new RB_SmallShops_Info_Extend { TenantId = userInfo.TenantId, MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId }).OrderByDescending(x => x.CreateDate).FirstOrDefault();
            if (oldList != null)
            {
                if (oldList.AuditStatus == DistributorAuditStatusEnum.Reject)
                {
                    return ApiResult.Failed("您之前的申请已被拒绝，不能修改");
                }

                else if (oldList.AuditStatus == DistributorAuditStatusEnum.Auditing)
                {
                    return ApiResult.Failed("您的申请审核中，不能修改");
                }
            }
            else
            {
                return ApiResult.Failed("您还未申请成为微店");
            }

            demodel.Id = oldList.Id;
            demodel.UpdateDate = System.DateTime.Now;
            bool flag = userModule.UpdateShopsInfo(demodel);
            if (flag)
            {
                return ApiResult.Success("", "更新成功");
            }
            else
            {
                return ApiResult.Failed("", "更新失败");
            }

        }




        /// <summary>
        /// 获取微店我的客户列表标题
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GerSmallShopsMyTeamTitelListForFX()
        {
            var userInfo = AppletUserInfo;

            var obj = userModule.GerSmallShopsMyTeamTitelListForFX(userInfo);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 获取微店我的客户列表
        /// </summary>
        /// <returns></returns>
        public ApiResult GetSmallShopsMyTeamPageListForFX()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pageModel = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_Distributor_Info_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Info_Extend>(req.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.SmallShopId;
            pageModel.pageData = userModule.GetSmallShopsMyTeamPageListForFX(pageModel.pageIndex, pageModel.pageSize, out long count, demodel);
            pageModel.count = Convert.ToInt32(count);

            return ApiResult.Success("", pageModel);
        }




        /// <summary>
        /// 获取分销中心
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSmallShopsCenter()
        {
            var userInfo = AppletUserInfo;

            var obj = userModule.GetSmallShopsCenter(userInfo);
            return ApiResult.Success("", obj);
        }


        /// <summary>
        /// 获取用户分销订单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSmallShopsCommissionPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_SmallShops_Commission_Extend demodel = JsonConvert.DeserializeObject<RB_SmallShops_Commission_Extend>(req.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.SmallShopsId = userInfo.SmallShopId;
            var list = smallShopsModule.GetSmallShopsCommissionPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                x.GradeDescription,
                DetailList = x.OrderDetailList.Select(y => new
                {
                    y.Id,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                    y.ProductCode,
                    y.Final_Price,
                    y.Number
                }),
                x.UserId,
                x.UserName,
                x.Photo,
                x.Mobile,
                x.Remark,
                x.Commission,
                x.CommissionState,
                StatusName = x.DistrbutionOrderSelectStatus == 1 ? "待付款" : x.DistrbutionOrderSelectStatus == 5 ? "已完成" : "已付款",
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }





        /// <summary>
        /// 获取微店提现明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSmallShopsRemitPageList()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_SmallShops_Remit_Extend demodel = JsonConvert.DeserializeObject<RB_SmallShops_Remit_Extend>(req.msg.ToString());

            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = smallShopsModule.GetSmallShopsRemitPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.OrderNum,
                x.WithdrawalWay,
                WithdrawalWayName = x.WithdrawalWay.GetEnumName(),
                x.AccountName,
                x.AccountNumber,
                x.BankName,
                x.AppliedMoney,
                x.Fee,
                x.RemitMoney,
                x.AuditRemark,
                x.RemitRemark,
                x.RejectRemark,
                x.AuditStatus,
                AuditStatusName = x.AuditStatus.GetEnumName(),
                x.TenantId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                AuditDate = x.AuditDate.HasValue ? x.AuditDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                RemitDate = x.RemitDate.HasValue ? x.RemitDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                RejectDate = x.RejectDate.HasValue ? x.RejectDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 微信小程序获取店铺信息
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [Microsoft.AspNetCore.Authorization.AllowAnonymous]
        public ApiResult GetSmallShopById(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            var query = JsonConvert.DeserializeObject<RB_SmallShops_Info_Extend>(requestParm.msg.ToString());
            RB_SmallShops_Info_Extend model = new RB_SmallShops_Info_Extend();

            if (model.UserId > 0)
            {
                var userModel = userModule.GetMemberUserInfo(model.UserId ?? 0);
                if (userModel != null && userModel.Id > 0 && userModel.SmallShopId > 0)
                {
                    query.Id = userModel.SmallShopId;
                }
            }
            if (query.Id > 0)
            {
                model = userModule.GetSmallShopsInfoList(new RB_SmallShops_Info_Extend { TenantId = model.TenantId, MallBaseId = model.MallBaseId, Id = query.Id }).OrderByDescending(x => x.CreateDate).FirstOrDefault();
            }
            if (model == null)
            {
                model = new RB_SmallShops_Info_Extend();
            }
            var result = new
            {
                model.Id,
                model.Logo,
                model.Name,
                model.Notice,
                PriceType = (model.PriceType ?? 0),
                UpPrice = (model.UpPrice ?? 0)
            };
            return ApiResult.Success("", result);
        }



        #endregion

        /// <summary>
        /// 修改会员等级为VIP
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        [Microsoft.AspNetCore.Authorization.AllowAnonymous]
        public ApiResult SetUserToVip(object requestMsg)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(requestMsg.ToString());
            JObject parms = JObject.Parse(requestParm.msg.ToString());
            var userId = parms.GetInt("NewUserId");
            bool flag = userModule.SetUserToVipModule(userId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
    }
}