using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
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 Mall.CacheManager.User;
using Newtonsoft.Json.Linq;
using Mall.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Google.Protobuf.WellKnownTypes;
using Dnc.Api.Throttle;

namespace Mall.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class UserController : BaseController
    {
        private readonly IHttpContextAccessor _accessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accessor"></param>
        public UserController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        /// <summary>
        /// 小程序用户处理类
        /// </summary>
        private readonly UserModule userModule = new UserModule();

        /// <summary>
        /// 小程序管理员处理类
        /// </summary>
        private readonly MiniprogramAdminModule adminModule = new MiniprogramAdminModule();

        /// <summary>
        /// 用户分组处理类对象
        /// </summary>
        private readonly MemberGroupModule memberGroupModule = new MemberGroupModule();

        #region 用户管理
        /// <summary>
        /// 获取用户分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberUserPageList()
        {
            var parms = RequestParm;
            JObject param = JObject.Parse(parms.msg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Member_User_Extend demodel = new RB_Member_User_Extend()
            {
                Name = param.GetStringValue("Name"),
                Source = (UserSourceEnum)param.GetInt("Source"),
                MemberGrade = param.GetInt("MemberGrade"),
                Id = param.GetInt("Id"),
                Moblie = param.GetStringValue("Moblie"),
                StartTime = param.GetStringValue("StartTime"),
                EndTime = param.GetStringValue("EndTime"),
            };
            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetMemberUserPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.AliasName,
                x.Balance,
                x.Blacklist,
                x.CardVolumeNum,
                x.ContactWay,
                x.CouponsNum,
                x.Integral,
                x.TotalConsumption,
                x.MemberGrade,
                x.MemberGradeName,
                x.Moblie,
                x.Name,
                x.OpenId,
                x.OrderNum,
                x.Photo,
                x.Remark,
                x.Source,
                SourceName = x.Source.GetEnumName(),
                x.TenantId,
                x.PostId,
                PostName = (x?.PostId ?? 0) == 1 ? "领队导游" : "",
                UserPageTypeStr = x.UserPageType.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 GetMemberUserDropDownList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetMemberUserDropDownList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.AliasName,
                x.Name
            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 获取结算用户下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberUserDropDownList_V2()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetMemberUserDropDownList_V2(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.AliasName,
                x.Name
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberUserInfo()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            int UserId = parms.GetInt("UserId", 0);
            if (UserId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var model = userModule.GetMemberUserInfo(UserId);
            if (model.TenantId != Convert.ToInt32(requestParm.uid))
            {
                return ApiResult.ParamIsNull("未查询到该用户信息");
            }
            if (model.MallBaseId != requestParm.MallBaseId)
            {
                return ApiResult.ParamIsNull("未查询到该用户信息");
            }
            string SuperiorName = "";
            if (model.SuperiorId > 0)
            {
                SuperiorName = userModule.GetMemberUserInfo(model.SuperiorId ?? 0)?.Name ?? "";
            }
            return ApiResult.Success("", new
            {
                model.Id,
                model.Photo,
                model.Name,
                model.AliasName,
                model.MemberGrade,
                model.SuperiorId,
                SuperiorName,
                model.Blacklist,
                model.ContactWay,
                model.Moblie,
                model.Remark,
                model.PostId,
                model.IsAdmin,
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
        }

        /// <summary>
        /// 后台更新用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMemberUserInfoForHT()
        {
            var parms = RequestParm;
            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(parms.msg.ToString());
            if (demodel.Id <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            var umodel = userModule.GetMemberUserInfo(demodel.Id);
            if (umodel == null)
            {
                return ApiResult.Failed("用户不存在");
            }
            if (umodel.TenantId != Convert.ToInt32(parms.uid))
            {
                return ApiResult.ParamIsNull("未查询到该用户信息");
            }
            if (umodel.MallBaseId != parms.MallBaseId)
            {
                return ApiResult.ParamIsNull("未查询到该用户信息");
            }
            //if (!(demodel.SuperiorId == 0 || demodel.SuperiorId == umodel.SuperiorId))
            //{
            //    return ApiResult.ParamIsNull("上级id有误");
            //}

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

        /// <summary>
        /// 用户信息下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetMemberUserListToExcel()
        {
            var parms = RequestParm;
            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(parms.msg.ToString());
            string ExcelName = "班级收支明细" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(UserExportEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30)
                {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = userModule.GetMemberUserList(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    foreach (var qitem in demodel.ExcelEnumIds)
                    {
                        switch (qitem)
                        {
                            case 1:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Source.GetEnumName()) { }); break;
                            case 2:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Id.ToString()) { }); break;
                            case 3:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.OpenId) { }); break;
                            case 4:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.AliasName ?? "") != "" ? item.AliasName : item.Name) { }); break;
                            case 5:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Moblie) { }); break;
                            case 6:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.ContactWay) { }); break;
                            case 7:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Remark) { }); break;
                            case 8:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                            case 9:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.MemberGradeName) { }); break;
                            case 10:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.OrderNum ?? 0).ToString()) { }); break;
                            case 11:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.CouponsNum ?? 0).ToString()) { }); break;
                            case 12:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.CardVolumeNum ?? 0).ToString()) { }); break;
                            case 13:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.Integral ?? 0).ToString()) { }); break;
                            case 14:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.Balance ?? 0).ToString()) { }); break;
                            case 15:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.TotalConsumption ?? 0).ToString()) { }); break;
                        }
                    }
                    slist.Add(datarow);
                }
                #endregion
                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
        }

        /// <summary>
        /// 获取用户下载枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberUserExcelEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(UserExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取用户平台枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberUserSourceEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(UserSourceEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取会员等级分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberGradePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Member_Grade_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Grade_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetMemberGradePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Grade,
                x.BackgroundImage,
                x.BackgroundImagePath,
                x.Discount,
                x.Enabled,
                EquityList = x.EquityList.Select(x => new
                {
                    x.Id,
                    x.Content,
                    x.Image,
                    x.ImagePath,
                    x.Title
                }),
                x.Icon,
                x.IconPath,
                x.IsAutoUpGrade,
                x.IsMemberBuy,
                x.MemberBuyMoney,
                x.MemberSpecification,
                x.TenantId,
                TenantName = UserReidsCache.GetUserLoginInfo(x.TenantId)?.Name ?? "",
                x.UpGradeMoney,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取会员等级列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberGradeList()
        {
            var parms = RequestParm;
            RB_Member_Grade_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Grade_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetMemberGradeList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Grade,
                x.Name,
                x.Icon,
                x.IconPath,
                x.BackgroundImage,
                x.BackgroundImagePath
            }));
        }

        /// <summary>
        /// 获取会员等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberGrade()
        {
            var parms = RequestParm;
            RB_Member_Grade_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Grade_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetMemberGrade(demodel);
            return ApiResult.Success("", list.Select(x => x.Grade).ToList());
        }

        /// <summary>
        /// 新增会员等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberGradeInfo()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            int GradeId = parms.GetInt("GradeId", 0);
            if (GradeId <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }

            var model = userModule.GetMemberGradeInfo(GradeId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.Name,
                model.Grade,
                model.BackgroundImage,
                model.BackgroundImagePath,
                model.Discount,
                model.Enabled,
                EquityList = model.EquityList.Select(x => new
                {
                    x.Id,
                    x.Content,
                    x.Image,
                    x.ImagePath,
                    x.Title
                }),
                model.Icon,
                model.IconPath,
                model.IsAutoUpGrade,
                model.IsMemberBuy,
                model.MemberBuyMoney,
                model.MemberSpecification,
                model.UpGradeMoney
            });
        }

        /// <summary>
        /// 新增会员等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMemberGradeInfo()
        {
            var parms = RequestParm;
            RB_Member_Grade_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Grade_Extend>(parms.msg.ToString());
            if (demodel.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull("请传递小程序");
            }
            if ((demodel.Grade ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递等级");
            }
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入等级名称");
            }
            if ((demodel.Discount ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请输入折扣率");
            }
            if ((demodel.Enabled ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请选择会员状态");
            }
            if ((demodel.Icon ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请选择会员图标");
            }
            if ((demodel.BackgroundImage ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请选择会员背景图");
            }
            if (demodel.IsAutoUpGrade == 1)
            {
                if ((demodel.UpGradeMoney ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请输入累计完成订单金额");
                }
            }
            else
            {
                demodel.IsAutoUpGrade = 2;
                demodel.UpGradeMoney = 0;
            }
            if (demodel.IsMemberBuy == 1)
            {
                if ((demodel.MemberBuyMoney ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请输入会员购买价格");
                }
            }
            else
            {
                demodel.IsMemberBuy = 2;
                demodel.MemberBuyMoney = 0;
            }

            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;
            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            if (userModule.ValidateMemberGrade(demodel))
            {
                return ApiResult.Failed("该等级已存在,请重新选择等级");
            }
            bool flag = userModule.SetMemberGradeInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除会员等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelMemberGradeInfo()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            int GradeId = parms.GetInt("GradeId", 0);
            if (GradeId <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }

            bool flag = userModule.DelMemberGradeInfo(GradeId, RequestParm.uid);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取会用户积分分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberIntegralPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Member_Integral_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Integral_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            List<RB_Member_Integral_Extend> list = userModule.GetMemberIntegralPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Type,
                x.Description,
                x.Image,
                x.Integral,
                x.UserId,
                x.TenantId,
                TenantName = UserReidsCache.GetUserLoginInfo(x.TenantId)?.Name ?? "",
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 新增积分
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMemberIntegralInfo()
        {
            var parms = RequestParm;
            RB_Member_Integral_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Integral_Extend>(parms.msg.ToString());
            if (demodel.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull("请传递小程序id");
            }
            if ((demodel.UserId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递用户id");
            }
            if ((int)demodel.Type != 1 && (int)demodel.Type != 2)
            {
                return ApiResult.ParamIsNull("请选择充值/扣除");
            }
            if ((demodel.Integral ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请输入积分数");
            }

            demodel.Description ??= "";
            demodel.Image ??= 0;
            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            bool flag = userModule.SetMemberIntegralInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }

        }

        /// <summary>
        /// 获取会用户余额分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberBalancePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Member_Balance_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Balance_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            List<RB_Member_Balance_Extend> list = userModule.GetMemberBalancePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Type,
                x.Description,
                x.Image,
                x.Balance,
                x.UserId,
                x.TenantId,
                TenantName = UserReidsCache.GetUserLoginInfo(x.TenantId)?.Name ?? "",
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 新增余额
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMemberBalanceInfo()
        {
            var parms = RequestParm;
            RB_Member_Balance_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Balance_Extend>(parms.msg.ToString());
            if (demodel.MallBaseId <= 0)
            {
                return ApiResult.ParamIsNull("请传递小程序id");
            }
            if ((demodel.UserId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递用户id");
            }
            if ((int)demodel.Type != 1 && (int)demodel.Type != 2)
            {
                return ApiResult.ParamIsNull("请选择充值/扣除");
            }
            if ((demodel.Balance ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请输入金额");
            }

            demodel.Description ??= "";
            demodel.Image ??= 0;
            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            bool flag = userModule.SetMemberBalanceInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }

        }



        /// <summary>
        /// 获取用户分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberBuyUserPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Member_Buy_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Buy_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            demodel.PayState = 1;
            var list = userModule.GetMemberBuyPageList(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,
                x.GradeName,
                PayTime = x.PayTime.HasValue ? x.PayTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 获取会员购买导出选项列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMembersToBuyExportEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(Common.Enum.Goods.MembersToBuyExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 会员购买Excel下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetMembersToBuyToExcel()
        {
            var parms = RequestParm;
            RB_Member_Buy_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Buy_Extend>(parms.msg.ToString());
            string ExcelName = "会员购买" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(Common.Enum.Goods.MembersToBuyExportEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                demodel.PayState = 1;
                var list = userModule.GetMemberBuyList(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {

                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    foreach (var qitem in demodel.ExcelEnumIds)
                    {
                        switch (qitem)
                        {
                            case 1:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderSource.GetEnumName()) { }); break;
                            case 2:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNo) { }); break;
                            case 3:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.UserName) { }); break;
                            case 4:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.Money ?? 0).ToString()) { }); break;
                            case 5:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.PayTime.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                            case 6:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.PayState == 0 ? "未支付" : "已支付") { }); break;
                        }
                    }
                    slist.Add(datarow);
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        #endregion

        #region 小程序管理员
        /// <summary>
        /// 获取小程序管理员分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMiniprogramAdminPage()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Miniprogram_Admin_Extend demodel = new RB_Miniprogram_Admin_Extend()
            {
                UserId = parms.GetInt("UserId"),
                Name=parms.GetStringValue("Name"),
                Source=(UserSourceEnum)parms.GetInt("Source"),
            };
            demodel.TenantId = Convert.ToInt32(RequestParm.uid);
            demodel.MallBaseId = RequestParm.MallBaseId;
            var list = adminModule.GetMiniprogramAdminPageModule(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.AdminId,
                x.UserId,
                x.Photo,
                x.Name,
                x.Moblie,
                x.OpenId,
                x.Source,
                SourceName=x.Source.GetEnumName(),
                CreateDate= Common.ConvertHelper.FormatTime(x.CreateDate),
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 新增修改小程序管理员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMiniprogramAdmin()
        {
            var parms = JObject.Parse(RequestParm.msg.ToString());
            RB_Miniprogram_Admin_Extend demodel = new RB_Miniprogram_Admin_Extend()
            {
                AdminId = parms.GetInt("AdminId"),
                CreateDate = DateTime.Now,
                MallBaseId = RequestParm.MallBaseId,
                TenantId = RequestParm.TenantId,
                Status = Common.Enum.DateStateEnum.Normal,
                UpdateDate = DateTime.Now,
                UserId = parms.GetInt("UserId"),
            };
            if (demodel.UserId <= 0)
            {
                return ApiResult.ParamIsNull(message:"请选择小程序用户!");
            }
            if (adminModule.CheckExistsAdminModule(demodel))
            {
                return ApiResult.Failed(message:"已存在此用户!");
            }

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

        /// <summary>
        /// 删除小程序管理员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DeleteMiniprogramAdmin()
        {
            var parms = JObject.Parse(RequestParm.msg.ToString());
            var AdminId = parms.GetInt("AdminId");
            if (AdminId <= 0)
            {
                return ApiResult.ParamIsNull(message: "请选择小程序用户!");
            }
            bool flag = adminModule.RemoveMiniprogramAdminModule(AdminId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 分销商基础

        /// <summary>
        /// 新增分销商基础
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDistributorBasicsInfo()
        {
            var requestParm = RequestParm;
            RB_Distributor_Basics_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Basics_Extend>(requestParm.msg.ToString());
            if (demodel.DistributorTier != 0 && demodel.DistributorTier != 1 && demodel.DistributorTier != 2 && demodel.DistributorTier != 3)
            {
                return ApiResult.ParamIsNull("请选择分销层级");
            }
            switch (demodel.DistributorTier)
            {
                case 0:
                    demodel.OneCommission = 0;
                    demodel.TwoCommission = 0;
                    demodel.ThreeCommission = 0;
                    break;
                case 1:
                    demodel.TwoCommission = 0;
                    demodel.ThreeCommission = 0;
                    break;
                case 2:
                    demodel.ThreeCommission = 0;
                    break;
            }

            if (demodel.WithdrawWayList == null || !demodel.WithdrawWayList.Any())
            {
                return ApiResult.ParamIsNull("请选择提现方式");
            }
            demodel.WithdrawWay = JsonConvert.SerializeObject(demodel.WithdrawWayList);
            demodel.OneCommission ??= 0;
            demodel.TwoCommission ??= 0;
            demodel.ThreeCommission ??= 0;
            demodel.IsCommissionResidue ??= 2;
            demodel.WithdrawFee ??= 0;
            demodel.MinimumWithdrawalLimit ??= 0;
            demodel.DailyWithdrawalLimit ??= 0;
            demodel.BackgroundImage ??= 0;
            demodel.IndexImage ??= 0;
            demodel.HpReferralsGradeAudit ??= 2;
            demodel.IsWithdrawAll ??= 2;
            demodel.IsEnableFXGrade ??= 2;
            demodel.IsEnableNoSuperiorFY ??= 1;
            demodel.TenantId = Convert.ToInt32(requestParm.uid);
            demodel.MallBaseId = requestParm.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = userModule.SetDistributorBasicsInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取分销商基础信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorBasicsInfo()
        {
            var requestParm = RequestParm;
            var model = userModule.GetDistributorBasicsInfo(requestParm.uid, requestParm.MallBaseId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.DistributorTier,
                model.InPurchasing,
                model.ReferralsCondition,
                model.ApplyFor,
                model.DistributorCondition,
                model.DistributorCommissionType,
                model.OneCommission,
                model.TwoCommission,
                model.ThreeCommission,
                model.GradeEntrance,
                model.GradeEntranceImage,
                model.WithdrawWay,
                model.WithdrawWayList,
                model.MinimumWithdrawalLimit,
                model.DailyWithdrawalLimit,
                model.WithdrawFee,
                model.ApplicationProtocol,
                model.UserNotes,
                model.BackgroundImage,
                model.BackgroundImagePath,
                model.IndexImage,
                model.IndexImagePath,
                model.IsCommissionResidue,
                model.HpReferralsGradeAudit,
                model.IsWithdrawAll,
                model.IsEnableFXGrade,
                model.IsEnableNoSuperiorFY,
                UpdateDate = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
        }

        /// <summary>
        /// 获取分销商下线条件枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistrbutorReferralsEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(DistrbutorReferralsEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取分销商提现枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistrbutorWithdrawWayEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(DistrbutorWithdrawWayEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取申请成为分销商枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorApplyForEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(DistributorApplyForEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取成为分销商条件枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorConditionEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(DistributorConditionEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }
        #endregion

        #region 分销商自定义

        /// <summary>
        /// 新增分销商自定义
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDistributorCustomInfo()
        {
            var requestParm = RequestParm;
            RB_Distributor_Custom_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Custom_Extend>(requestParm.msg.ToString());
            if (demodel.HeadImage == null || string.IsNullOrWhiteSpace(demodel.HeadImage))
            {
                return ApiResult.ParamIsNull("请传递分销申请下头部图片");
            }
            if (demodel.BottomImage == null || string.IsNullOrWhiteSpace(demodel.BottomImage))
            {
                return ApiResult.ParamIsNull("请传递分销申请下底部图片");
            }
            if (string.IsNullOrEmpty(demodel.DistributionApplication))
            {
                return ApiResult.ParamIsNull("请传递分销申请下分销申请");
            }
            if (string.IsNullOrEmpty(demodel.ApplicationAgreement))
            {
                return ApiResult.ParamIsNull("请传递分销申请下分销申请协议");
            }
            if (string.IsNullOrEmpty(demodel.ButtonText))
            {
                return ApiResult.ParamIsNull("请传递分销申请下按钮文本");
            }
            if (string.IsNullOrEmpty(demodel.ButtonColor))
            {
                return ApiResult.ParamIsNull("请传递分销申请下填充颜色");
            }
            if (string.IsNullOrEmpty(demodel.ButtonTextColor))
            {
                return ApiResult.ParamIsNull("请传递分销申请下文本颜色");
            }

            if (string.IsNullOrEmpty(demodel.DistributionCommissionName))
            {
                return ApiResult.ParamIsNull("请传递分销中心下分销佣金");
            }
            if (demodel.DistributionCommissionImage == null || string.IsNullOrWhiteSpace(demodel.DistributionCommissionImage))
            {
                return ApiResult.ParamIsNull("请传递分销中心下分销佣金图片");
            }
            if (string.IsNullOrEmpty(demodel.DistributionOrderName))
            {
                return ApiResult.ParamIsNull("请传递分销中心下分销订单");
            }
            if (demodel.DistributionOrderImage == null || string.IsNullOrWhiteSpace(demodel.DistributionOrderImage))
            {
                return ApiResult.ParamIsNull("请传递分销中心下分销订单图片");
            }
            if (string.IsNullOrEmpty(demodel.WithdrawDetialsName))
            {
                return ApiResult.ParamIsNull("请传递分销中心下提现明细");
            }
            if (demodel.WithdrawDetialsImage == null || string.IsNullOrWhiteSpace(demodel.WithdrawDetialsImage))
            {
                return ApiResult.ParamIsNull("请传递分销中心下提现明细图片");
            }
            if (string.IsNullOrEmpty(demodel.MyTeamName))
            {
                return ApiResult.ParamIsNull("请传递分销中心下我的团队");
            }
            if (demodel.MyTeamImage == null || string.IsNullOrWhiteSpace(demodel.MyTeamImage))
            {
                return ApiResult.ParamIsNull("请传递分销中心下我的团队图片");
            }
            if (string.IsNullOrEmpty(demodel.PromoteQRCodeName))
            {
                return ApiResult.ParamIsNull("请传递分销中心下推广二维码");
            }
            if (demodel.PromoteQRCodeImage == null || string.IsNullOrWhiteSpace(demodel.PromoteQRCodeImage))
            {
                return ApiResult.ParamIsNull("请传递分销中心下推广二维码图片");
            }
            //
            if (string.IsNullOrEmpty(demodel.ReferrerName))
            {
                return ApiResult.ParamIsNull("请传递分销中心下推荐人");
            }
            if (string.IsNullOrEmpty(demodel.CommissionForWithdrawalName))
            {
                return ApiResult.ParamIsNull("请传递分销中心下可提现佣金");
            }
            if (string.IsNullOrEmpty(demodel.WithdrawDepositName))
            {
                return ApiResult.ParamIsNull("请传递分销中心下提现");
            }
            if (string.IsNullOrEmpty(demodel.CommissionWithdrawnName))
            {
                return ApiResult.ParamIsNull("请传递分销中心下已提现佣金");
            }
            if (string.IsNullOrEmpty(demodel.OutstandingCommissionName))
            {
                return ApiResult.ParamIsNull("请传递分销中心下未结算佣金");
            }
            if (string.IsNullOrEmpty(demodel.DistributorName))
            {
                return ApiResult.ParamIsNull("请传递分销中心下分销商");
            }
            //
            if (string.IsNullOrEmpty(demodel.CommissionTobePaidName))
            {
                return ApiResult.ParamIsNull("请传递分销佣金下待打款佣金");
            }
            if (string.IsNullOrEmpty(demodel.UserNotesName))
            {
                return ApiResult.ParamIsNull("请传递分销佣金下用户须知");
            }
            if (string.IsNullOrEmpty(demodel.IWantToWithdrawName))
            {
                return ApiResult.ParamIsNull("请传递分销佣金下我要提现");
            }
            //
            if (string.IsNullOrEmpty(demodel.WithdrawalAmountName))
            {
                return ApiResult.ParamIsNull("请传递申请提现下提现金额");
            }
            if (string.IsNullOrEmpty(demodel.WithdrawalWayName))
            {
                return ApiResult.ParamIsNull("请传递申请提现下提现方式");
            }
            //
            if (string.IsNullOrEmpty(demodel.OneDistributionName))
            {
                return ApiResult.ParamIsNull("请传递分销商下一级分销名称");
            }
            if (string.IsNullOrEmpty(demodel.TwoDistributionName))
            {
                return ApiResult.ParamIsNull("请传递分销商下二级分销名称");
            }
            if (string.IsNullOrEmpty(demodel.ThreeDistributionName))
            {
                return ApiResult.ParamIsNull("请传递分销商下三级分销名称");
            }
            if (string.IsNullOrWhiteSpace(demodel.VipBuyUrl))
            {
                return ApiResult.Failed("VIP购买链接不能为空");
            }
            if (string.IsNullOrWhiteSpace(demodel.VipBuyICO))
            {
                return ApiResult.Failed("VIP购买链接图标不能为空");
            }

            demodel.TenantId = Convert.ToInt32(requestParm.uid);
            demodel.MallBaseId = requestParm.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = userModule.SetDistributorCustomInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取分销商自定义
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorCustomInfo()
        {
            var requestParm = RequestParm;
            var model = userModule.GetDistributorCustomInfo(requestParm.uid, requestParm.MallBaseId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.HeadImage,
                model.HeadImagePath,
                model.BottomImage,
                model.BottomImagePath,
                model.DistributionApplication,
                model.ApplicationAgreement,
                model.ButtonFilletPX,
                model.ButtonText,
                model.ButtonColor,
                model.ButtonTextColor,
                model.DistributionCommissionName,
                model.DistributionCommissionImage,
                model.DistributionCommissionImagePath,
                model.DistributionOrderName,
                model.DistributionOrderImage,
                model.DistributionOrderImagePath,
                model.WithdrawDetialsName,
                model.WithdrawDetialsImage,
                model.WithdrawDetialsImagePath,
                model.MyTeamName,
                model.MyTeamImage,
                model.MyTeamImagePath,
                model.PromoteQRCodeName,
                model.PromoteQRCodeImage,
                model.PromoteQRCodeImagePath,
                model.ReferrerName,
                model.CommissionForWithdrawalName,
                model.WithdrawDepositName,
                model.CommissionWithdrawnName,
                model.OutstandingCommissionName,
                model.DistributorName,
                model.CommissionTobePaidName,
                model.UserNotesName,
                model.IWantToWithdrawName,
                model.WithdrawalAmountName,
                model.WithdrawalWayName,
                model.OneDistributionName,
                model.TwoDistributionName,
                model.ThreeDistributionName,
                UpdateDate = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                model.VipBuyICO,
                model.VipBuyUrl,
                model.IsShowVIPBuyPic,
                model.OpenOfflineEarnings
            });
        }

        #endregion

        #region 分销商等级

        /// <summary>
        /// 获取分销商等级分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorGradePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Distributor_Grade_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Grade_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetDistributorGradePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Grade,
                x.IsAutoUpGrade,
                x.UpGradeCondition,
                x.ReferralsNumber,
                x.TotalCommission,
                x.CommissionWithdrawn,
                x.DistributionCommissionType,
                x.OneCommission,
                x.TwoCommission,
                x.ThreeCommission,
                x.Enabled,
                x.GradeExplain,
                x.TenantId,
                x.MallBaseId,
                UpdateDate = x.UpdateDate.HasValue ? x.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取分销等级下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorGradeDropdownList()
        {
            var parms = RequestParm;
            RB_Distributor_Grade_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Grade_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetDistributorGradeDropdownList(demodel);

            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Grade
            }));
        }

        /// <summary>
        /// 获取分销层级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorTierInfo()
        {
            var requestParm = RequestParm;
            var model = userModule.GetDistributorBasicsInfo(requestParm.uid, requestParm.MallBaseId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.DistributorTier
            });
        }

        /// <summary>
        /// 获取分销商等级详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorGradeInfo()
        {
            var re = RequestParm;
            var parms = JObject.Parse(re.msg.ToString());
            int GradeId = parms.GetInt("GradeId", 0);
            if (GradeId <= 0)
            {
                return ApiResult.ParamIsNull("请传递等级id");
            }

            var model = userModule.GetDistributorGradeInfo(GradeId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.Name,
                model.Grade,
                model.IsAutoUpGrade,
                model.UpGradeCondition,
                model.ReferralsNumber,
                model.TotalCommission,
                model.CommissionWithdrawn,
                model.DistributionCommissionType,
                model.OneCommission,
                model.TwoCommission,
                model.ThreeCommission,
                model.Enabled,
                model.GradeExplain,
                model.TenantId,
                model.MallBaseId,
            });
        }

        /// <summary>
        /// 新增修改分销商等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDistributorGradeInfo()
        {
            var re = RequestParm;
            RB_Distributor_Grade_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Grade_Extend>(re.msg.ToString());
            if ((demodel.Grade ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递等级");
            }
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请输入等级名称");
            }
            if (demodel.IsAutoUpGrade == 1)
            {
                if (demodel.UpGradeCondition == DistrbutorGradeUpdateEnum.XXYHS)
                {
                    if ((demodel.ReferralsNumber ?? 0) <= 0)
                    {
                        return ApiResult.ParamIsNull("请传递下线用户数量");
                    }
                }
                if (demodel.UpGradeCondition == DistrbutorGradeUpdateEnum.LJYJ)
                {
                    if ((demodel.TotalCommission ?? 0) <= 0)
                    {
                        return ApiResult.ParamIsNull("请传递累计佣金金额");
                    }
                }
                if (demodel.UpGradeCondition == DistrbutorGradeUpdateEnum.YTXYJ)
                {
                    if ((demodel.CommissionWithdrawn ?? 0) <= 0)
                    {
                        return ApiResult.ParamIsNull("请传递已提现佣金金额");
                    }
                }
            }
            var model = userModule.GetDistributorBasicsInfo(re.uid, re.MallBaseId);
            if (model == null)
            {
                return ApiResult.ParamIsNull("请先配置分销商基础信息");
            }
            switch (model.DistributorTier)
            {
                case 0:
                    demodel.OneCommission = 0;
                    demodel.TwoCommission = 0;
                    demodel.ThreeCommission = 0;
                    break;
                case 1:
                    demodel.TwoCommission = 0;
                    demodel.ThreeCommission = 0;
                    break;
                case 2:
                    demodel.ThreeCommission = 0;
                    break;
            }
            demodel.OneCommission ??= 0;
            demodel.TwoCommission ??= 0;
            demodel.ThreeCommission ??= 0;
            demodel.Enabled ??= 1;

            demodel.TenantId = Convert.ToInt32(re.uid);
            demodel.MallBaseId = re.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;
            bool flag = userModule.SetDistributorGradeInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 新增修改分销商等级启用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDistributorGradeEnabledStatus()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GradeId = parms.GetInt("GradeId", 0);
            if (GradeId <= 0)
            {
                return ApiResult.ParamIsNull("请传递等级id");
            }
            var model = userModule.GetDistributorGradeInfo(GradeId);
            if (model == null)
            {
                return ApiResult.ParamIsNull("信息不存在，核实后再试");
            }
            if (model.Enabled == 1)
            {
                //验证是否有分销商在使用该等级
                if (userModule.ValidateDistributorGradeEnabled(GradeId))
                {
                    return ApiResult.ParamIsNull("该等级由分销商正在使用，无法停用");
                }
            }

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

        /// <summary>
        /// 删除会员等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelDistributorGradeInfo()
        {
            var re = RequestParm;
            var parms = JObject.Parse(re.msg.ToString());
            int GradeId = parms.GetInt("GradeId", 0);
            if (GradeId <= 0)
            {
                return ApiResult.ParamIsNull("请传递等级id");
            }

            bool flag = userModule.DelDistributorGradeInfo(GradeId, re.uid, re.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取分销商升级条件枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistrbutorGradeUpdateEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(DistrbutorGradeUpdateEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }


        #endregion

        #region 分销商申请管理

        /// <summary>
        /// 获取分销商分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorInfoPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            var parameters = JObject.Parse(RequestParm.msg.ToString());
            RB_Distributor_Info_Extend demodel = new RB_Distributor_Info_Extend()
            {
                UserId = parameters.GetInt("UserId"),
                AuditStatus = (DistributorAuditStatusEnum)parameters.GetInt("AuditStatus"),
                GradeId = parameters.GetInt("GradeId"),
                Name = parameters.GetStringValue("Name"),
                Source = (UserSourceEnum)parameters.GetInt("Source"),
                NickName = parameters.GetStringValue("NickName"),
                Mobile = parameters.GetStringValue("Mobile")
            };

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetDistributorInfoPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.UserId,
                x.NickName,
                x.Photo,
                x.Source,
                x.Name,
                x.Mobile,
                x.CommissionWithdrawal,
                x.TotalCommission,
                x.SuperiorId,
                x.SuperiorName,
                x.OneNum,
                x.TwoNum,
                x.ThreeNum,
                x.GradeId,
                x.GradeName,
                x.HPGradeId,
                x.HPGradeName,
                x.FXGradeId,
                x.FXGradeName,
                x.AuditStatus,
                AuditStatusName = x.AuditStatus.GetEnumName(),
                x.Remark,
                SourceName = x.Source.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") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取分销商下线
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorInfoReferralsList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Distributor_Info_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Info_Extend>(parms.msg.ToString());

            if ((demodel.UserId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetDistributorInfoReferralsPageList(demodel);
            var model = userModule.GetMemberUserInfo(demodel.UserId ?? 0);

            return ApiResult.Success("", list.Select(x => new
            {
                DistributorName = model.Name,
                demodel.ReferralsType,
                x.Name,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
            }));
        }

        /// <summary>
        /// 获取分销商审核状态枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorAuditStatusEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(DistributorAuditStatusEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 新增分销商申请
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDistributorInfo()
        {
            var req = RequestParm;
            RB_Distributor_Info_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Info_Extend>(req.msg.ToString());
            if ((demodel.UserId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递用户id");
            }
            if (demodel.IsFormSelfApplication == 1)
            {
                if (string.IsNullOrEmpty(demodel.Name))
                {
                    return ApiResult.ParamIsNull("请传递姓名");
                }
                if (string.IsNullOrEmpty(demodel.Mobile))
                {
                    return ApiResult.ParamIsNull("请传递手机号码");
                }
            }

            demodel.TenantId = Convert.ToInt32(req.uid);
            demodel.MallBaseId = req.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            demodel.Status = 0;
            //验证用户是否已是分销商
            string msg = userModule.ValidateDistributorInfo(demodel.UserId, demodel.TenantId, demodel.MallBaseId);
            if (msg != "")
            {
                return ApiResult.Failed(msg);
            }

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

        /// <summary>
        /// 分销商申请审核
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDistributorAudit()
        {
            var re = RequestParm;
            var parms = JObject.Parse(re.msg.ToString());
            string UserIds = parms.GetStringValue("UserIds");
            int Type = parms.GetInt("Type", 0);//1审核通过  2审核拒绝  3删除分销  4修改等级  5修改备注  6修改和平分销等级  7修改粉象分销等级
            int NewGradeId = parms.GetInt("NewGradeId", 0);
            string Remark = parms.GetStringValue("Remark");
            if (string.IsNullOrEmpty(UserIds))
            {
                return ApiResult.ParamIsNull("请传递用户id");
            }
            if (Type == 4)
            {
                if (NewGradeId <= 0)
                {
                    return ApiResult.ParamIsNull("请传递分销商等级");
                }
            }

            string msg = userModule.SetDistributorAudit(UserIds, Type, NewGradeId, Remark, re.uid, re.MallBaseId, re.EmpId);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取分销二维码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorQRCode()
        {
            //小程序接口
            return ApiResult.Success();
        }

        /// <summary>
        /// 获取分销商下载枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorExportEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(DistributorExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 分销商信息下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetDistributorListToExcel()
        {
            var parms = RequestParm;
            RB_Distributor_Info_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Info_Extend>(parms.msg.ToString());
            string ExcelName = "分销商列表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(DistributorExportEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = userModule.GetDistributorInfoList(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    foreach (var qitem in demodel.ExcelEnumIds)
                    {
                        switch (qitem)
                        {
                            case 1:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Source.GetEnumName()) { }); break;
                            case 2:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.UserId ?? 0).ToString()) { }); break;
                            case 3:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.NickName ?? "") { }); break;
                            case 4:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Name ?? "") { }); break;
                            case 5:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Mobile ?? "") { }); break;
                            case 6:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                            case 7:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.AuditStatus.GetEnumName()) { }); break;
                            case 8:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.TotalCommission ?? 0).ToString()) { }); break;
                            case 9:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.CommissionWithdrawal ?? 0).ToString()) { }); break;
                            case 10:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.OrderNum ?? 0).ToString()) { }); break;
                            case 11:
                                datarow.ExcelRows.Add(new ExcelColumn(value: "一级:" + (item.OneNum ?? 0) + " 二级:" + (item.TwoNum ?? 0) + " 三级:" + (item.ThreeNum ?? 0)) { }); break;
                            case 12:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.SuperiorName ?? "") { }); break;
                            case 13:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Remark ?? "") { }); break;
                        }
                    }
                    slist.Add(datarow);
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }

        /// <summary>
        /// 设置分销商佣金
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDistributorCommission()
        {
            var re = RequestParm;
            var parms = JObject.Parse(re.msg.ToString());
            int DistributorId = parms.GetInt("DistributorId", 0);
            decimal Money = parms.GetDecimal("Money");
            if (DistributorId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            if (Money < 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = userModule.SetDistributorCommission(DistributorId, Money, re.uid, re.MallBaseId, re.EmpId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 分销商提现

        /// <summary>
        /// 获取分销商提现分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorRemitPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Distributor_Remit_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Remit_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.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.UserId,
                x.UserName,
                x.Photo,
                x.Source,
                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(),
                SourceName = x.Source.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 GetDistributorFeeInfo()
        {
            var requestParm = RequestParm;
            var model = userModule.GetDistributorBasicsInfo(requestParm.uid, requestParm.MallBaseId);
            return ApiResult.Success("", new
            {
                model.Id,
                model.WithdrawFee
            });
        }

        /// <summary>
        /// 申请分销提现
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDistributorRemitInfo()
        {
            var req = RequestParm;
            RB_Distributor_Remit_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Remit_Extend>(req.msg.ToString());
            if ((demodel.UserId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递用户id");
            }
            if ((demodel.WithdrawalWay ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递提现方式");
            }
            if ((demodel.AppliedMoney ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请输入提现金额");
            }
            var basmodel = userModule.GetDistributorBasicsInfo(req.uid, req.MallBaseId);
            decimal fee = (demodel.AppliedMoney ?? 0) * (basmodel?.WithdrawFee ?? 0) / 100;
            if (demodel.Fee != fee)
            {
                return ApiResult.ParamIsNull("手续费计算有误，请刷新后再试");
            }

            demodel.RemitMoney = (demodel.AppliedMoney ?? 0) - (demodel.Fee ?? 0);
            demodel.TenantId = Convert.ToInt32(req.uid);
            demodel.MallBaseId = req.MallBaseId;
            demodel.AuditStatus = DistributorRemitAuditStatusEnum.Auditing;
            demodel.RemitMoney ??= 0;
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNum = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            demodel.CreateDate = DateTime.Now;
            string msg = userModule.SetDistributorRemitInfo(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 分销提现申请审核
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDistributorRemitAudit()
        {
            var re = RequestParm;
            var parms = JObject.Parse(re.msg.ToString());
            int RemitId = parms.GetInt("RemitId", 0);
            int ErpEmpId = parms.GetInt("ErpEmpId", 0);//erp用户id
            if (ErpEmpId <= 0)
            {
                ErpEmpId = re.ERPEmpId;
            }
            int Type = parms.GetInt("Type", 0);//1审核通过  2打款  3驳回 
            string Remark = parms.GetStringValue("Remark");
            if (RemitId <= 0)
            {
                return ApiResult.ParamIsNull("请传递分销提现id");
            }
            var model = userModule.GetDistributorEntity(RemitId);
            if (model == null)
            {
                return ApiResult.Failed("该提现不存在，请核实后再试");
            }
            if (model.TenantId != Convert.ToInt32(re.uid))
            {
                return ApiResult.Failed("未查询到提现信息");
            }
            if (model.MallBaseId != re.MallBaseId)
            {
                return ApiResult.Failed("未查询到提现信息");
            }
            if (Type == 1)
            {
                if (model.AuditStatus != Common.Enum.User.DistributorRemitAuditStatusEnum.Auditing)
                {
                    return ApiResult.Failed("状态不对，请核实后再试");
                }
            }
            else if (Type == 2)
            {
                if (model.AuditStatus != Common.Enum.User.DistributorRemitAuditStatusEnum.ToPlayWith)
                {
                    return ApiResult.Failed("状态不对，请核实后再试");
                }
                //执行发放金额
                if (model.WithdrawalWay == DistrbutorWithdrawWayEnum.ZDDK)
                {
                    int IsNormalServer = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("IsNormalServer").Value);
                    if (IsNormalServer == 1)
                    {
                        var mallModel = userModule.GetMiniProgramExtend(re.MallBaseId);
                        var umodel = userModule.GetMemberUserInfo(model.UserId ?? 0);
                        var flag = App_Code.PayUtil.GetTransfersOrder(model.OrderNum, model.RemitMoney ?? 0, (model.UserId ?? 0).ToString(), umodel.OpenId, mallModel, _accessor);
                        if (flag)
                        {
                            string msg1 = userModule.SetDistributorRemitAudit(RemitId, Type, Remark, re.uid, re.MallBaseId, 0);
                            if (msg1 != "")
                            {
                                LogHelper.Write("提现：" + RemitId + "，失败");
                            }

                            new MiniProgramMsgModule().SendWithdrawSucceedMsg(model.TenantId, model.MallBaseId, umodel.OpenId, (model.RemitMoney ?? 0).ToString(), (model.Fee ?? 0).ToString(), (model.WithdrawalWay.GetEnumName()), "已发放佣金，请注意查收");
                            return ApiResult.Success();
                        }
                        else
                        {
                            LogHelper.Write("企业付款失败RemitId:" + RemitId);
                            return ApiResult.Failed("支付失败");
                        }
                    }
                    else
                    {
                        string msg1 = userModule.SetDistributorRemitAudit(RemitId, Type, Remark, re.uid, re.MallBaseId, 0);
                        if (msg1 != "")
                        {
                            return ApiResult.Failed("提现：" + RemitId + "，失败");
                        }
                        return ApiResult.Success();
                    }
                }
                else if (model.WithdrawalWay == DistrbutorWithdrawWayEnum.YETX)
                {
                    //把钱充值到余额里  在更新完提现表状态后 发放到余额

                }
                else
                {
                    return ApiResult.Failed("暂不支持该类型打款");
                }
            }
            else if (Type == 3)
            {
                if (model.AuditStatus != Common.Enum.User.DistributorRemitAuditStatusEnum.Auditing && model.AuditStatus != Common.Enum.User.DistributorRemitAuditStatusEnum.ToPlayWith)
                {
                    return ApiResult.Failed("状态不对，请核实后再试");
                }
            }
            else
            {
                return ApiResult.Failed("暂不支持该类型");
            }

            string msg = userModule.SetDistributorRemitAudit(RemitId, Type, Remark, re.uid, re.MallBaseId, ErpEmpId);
            if (msg == "")
            {
                if (Type == 3)
                {
                    var umodel = userModule.GetMemberUserInfo(model.UserId ?? 0);
                    new MiniProgramMsgModule().SendWithdrawFailMsg(model.TenantId, model.MallBaseId, umodel.OpenId, (model.RemitMoney ?? 0).ToString(), "提现申请已被拒绝");
                }
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        /// <summary>
        /// 获取分销提现审核状态枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorRemitAuditStatusEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(DistributorRemitAuditStatusEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 获取分销提现下载枚举列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorRemitExportEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(DistributorRemitExportEnum));
            return ApiResult.Success("", list.Select(x => new
            {
                Name = x.Key,
                Id = Convert.ToInt32(x.Value)
            }));
        }

        /// <summary>
        /// 分销提现信息下载
        /// </summary>
        [HttpPost]
        public FileContentResult GetDistributorRemitListToExcel()
        {
            var parms = RequestParm;
            RB_Distributor_Remit_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Remit_Extend>(parms.msg.ToString());
            string ExcelName = "提现列表" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            if (demodel.ExcelEnumIds == null || !demodel.ExcelEnumIds.Any())
            {
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
            var Enumlist = EnumHelper.GetEnumList(typeof(DistributorRemitExportEnum));
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                }
            };
            foreach (var item in demodel.ExcelEnumIds)
            {
                var Name = Enumlist.Where(x => x.Value == item.ToString()).FirstOrDefault().Key ?? "";
                header.ExcelRows.Add(new ExcelColumn(value: Name) { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER });
            }

            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = userModule.GetDistributorRemitList(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    foreach (var qitem in demodel.ExcelEnumIds)
                    {
                        switch (qitem)
                        {
                            case 1:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.Source.GetEnumName()) { }); break;
                            case 2:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNum ?? "") { }); break;
                            case 3:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.UserName ?? "") { }); break;
                            case 4:
                                datarow.ExcelRows.Add(new ExcelColumn(value: (item.AppliedMoney ?? 0).ToString()) { }); break;
                            case 5:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")) { }); break;
                            case 6:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.BankName ?? "") { }); break;
                            case 7:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.AccountNumber ?? "") { }); break;
                            case 8:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.AccountName ?? "") { }); break;
                            case 9:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.AuditStatus.GetEnumName()) { }); break;
                            case 10:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.WithdrawalWay.GetEnumName()) { }); break;
                            case 11:
                                datarow.ExcelRows.Add(new ExcelColumn(value: item.RemitDate.HasValue ? item.RemitDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { }); break;
                        }
                    }
                    slist.Add(datarow);
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }


        #endregion

        #region 数据统计-分销排行


        /// <summary>
        /// 获取用户下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetListByPhoneOrAliasName()
        {
            var parms = RequestParm;
            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(parms.msg.ToString());
            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            if (string.IsNullOrWhiteSpace(demodel.AliasName))
            {
                return ApiResult.Failed("请传入您要查找的信息");
            }
            var list = userModule.GetListByPhoneOrAliasName(demodel).Take(50);
            var result = list.Select(x => new
            {
                x.Id,
                AliasName = x.Name,
                x.Moblie,
                x.Photo
            });
            return ApiResult.Success("", result);
        }




        /// <summary>
        /// 获取用户列表-自动发放优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPageListByKey()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetPageListByKey(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.AliasName,
                x.Name,
                x.Source,
                x.Photo
            });
            return ApiResult.Success("", pagelist);
        }




        [HttpPost]
        public ApiResult GetRankingListPage()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(parms.msg.ToString());
            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetRankingListPage(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                AliasName = x.Name,
                x.Photo,
                x.Price,
                x.Source,
                x.ChildrenNum,
                x.AllChildrenNum,
                x.AllOrderNum,
                x.Commission,
                x.TotalCommission
            });
            return ApiResult.Success("", pagelist);
        }



        /// <summary>
        /// 导出分销排行
        /// </summary>
        [HttpPost]
        public FileContentResult GetRankingListToExcel()
        {
            var parms = RequestParm;
            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(parms.msg.ToString());
            string ExcelName = "分销排行" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                     new ExcelColumn(value: "ID") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                      new ExcelColumn(value: "分销商") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                       new ExcelColumn(value: "直接下级数量") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                           new ExcelColumn(value: "总下级数量") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                               new ExcelColumn(value: "分销商订单数") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                                   new ExcelColumn(value: "总佣金") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                                       new ExcelColumn(value: "累计佣金") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                                        new ExcelColumn(value: "已提现佣金") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER }
                },
            };
            slist.Add(header);

            try
            {
                demodel.TenantId = Convert.ToInt32(parms.uid);
                demodel.MallBaseId = parms.MallBaseId;
                var list = userModule.GetRankingList(demodel);
                #region 组装数据
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                            new ExcelColumn(value:Num.ToString()){ },
                        }
                    };
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Id.ToString()) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.AliasName) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.ChildrenNum.ToString()) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.AllChildrenNum.ToString()) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.AllOrderNum.ToString()) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Commission.ToString()) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.TotalCommission.ToString()) { });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.Price.ToString()) { });
                    slist.Add(datarow);
                }
                #endregion

                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetFileFromWebApi_requestData: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }

        }
        #endregion

        #region 用户转移

        /// <summary>
        /// 更新微信用户头像 (在控制台)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdateUserPhotoForWeiXin()
        {

            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int Count = parms.GetInt("Count", 1);
            int UserId = parms.GetInt("UserId", 0);
            if (Count == 0) { Count = 1; }
            if (UserId <= 0 && Count == 0)
            {
                return ApiResult.ParamIsNull();
            }
            bool flag = userModule.UpdateUserPhotoForWeiXin(UserId, Count, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 更新用户上下级关系
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult UpdateUserSuperiorForWeiXin()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int Count = parms.GetInt("Count", 1);
            int UserId = parms.GetInt("UserId", 0);
            if (Count == 0) { Count = 1; }
            if (UserId <= 0 && Count == 0)
            {
                return ApiResult.ParamIsNull();
            }
            int MaxId = userModule.UpdateUserSuperiorForWeiXin(UserId, Count, req.TenantId, req.MallBaseId);
            if (MaxId > 0)
            {
                return ApiResult.Success("", MaxId);
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 和平分销

        /// <summary>
        /// 获取和平分销等级信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetHpDistributorGradePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Distributor_HPGradeInfo_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_HPGradeInfo_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetHpDistributorGradePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Grade,
                x.GradeName,
                x.IsGuest,
                UpdateDate = x.UpdateDate.HasValue ? x.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取和平分销等级信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetHpDistributorGradeList()
        {
            var parms = RequestParm;
            RB_Distributor_HPGradeInfo_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_HPGradeInfo_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetHpDistributorGradeList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Grade,
                x.GradeName
            }));
        }

        /// <summary>
        /// 新增修改等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetHpDistributorGradeInfo()
        {
            var req = RequestParm;
            RB_Distributor_HPGradeInfo_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_HPGradeInfo_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.GradeName))
            {
                return ApiResult.ParamIsNull("等级名称");
            }
            if ((demodel.Grade ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请选择等级");
            }

            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.Status = 0;
            demodel.IsGuest ??= 2;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = userModule.SetHpDistributorGradeInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelHpDistributorGradeInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GradeId = parms.GetInt("GradeId", 0);
            if (GradeId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = userModule.DelHpDistributorGradeInfo(GradeId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取和平分销返佣分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetHpDistributorPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Distributor_HPCommission_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_HPCommission_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetHpDistributorPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.DecimalType,
                x.Enabled,
                x.IsCommon,
                CategoryList = x.CategoryList.Select(y => new
                {
                    y.Id,
                    y.CategoryId,
                    y.CategoryName
                }),
                RatioList = x.RatioList.Select(z => new
                {
                    z.Id,
                    z.GradeId,
                    z.GradeName,
                    z.CommissionRatio
                }),
                UpdateDate = x.UpdateDate.HasValue ? x.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetHpdistributorInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int CommissionId = parms.GetInt("CommissionId", 0);
            if (CommissionId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var model = userModule.GetHpdistributorInfo(CommissionId, req.TenantId, req.MallBaseId);

            return ApiResult.Success("", new
            {
                model.Id,
                model.Name,
                model.DecimalType,
                model.Enabled,
                model.IsCommon,
                CategoryList = model.CategoryList.Select(y => new
                {
                    y.Id,
                    y.CategoryId,
                    y.CategoryName
                }),
                RatioList = model.RatioList.Select(z => new
                {
                    z.Id,
                    z.GradeId,
                    z.GradeName,
                    z.CommissionRatio
                }),
                UpdateDate = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
            });
        }

        /// <summary>
        /// 新增修改和平分销返佣
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetHpDistributorInfo()
        {
            var req = RequestParm;
            RB_Distributor_HPCommission_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_HPCommission_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.ParamIsNull("请传递和平分销返佣名称");
            }
            if ((demodel.DecimalType ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请选择小数类型");
            }
            if (demodel.RatioList == null || !demodel.RatioList.Any())
            {
                return ApiResult.ParamIsNull("请选择返佣等级");
            }
            foreach (var item in demodel.RatioList)
            {
                if (item.GradeId <= 0)
                {
                    return ApiResult.ParamIsNull("请传递等级id");
                }
                if ((item.CommissionRatio ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请传递等级返佣比例");
                }
                if (item.CommissionRatio > 100)
                {
                    return ApiResult.ParamIsNull("返佣比例有误，不能大于100");
                }
            }
            demodel.IsCommon = 2;
            if (demodel.CategoryList == null || !demodel.CategoryList.Any())
            {
                demodel.IsCommon = 1;//通用
            }

            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.Enabled ??= 2;
            demodel.Status = 0;
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = userModule.SetHpDistributorInfo(demodel);
            if (flag) { return ApiResult.Success(); } else { return ApiResult.Failed(); }
        }

        /// <summary>
        /// 和平分销启用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGetHpDistributorEnabled()
        {
            var req = RequestParm;
            JObject prams = JObject.Parse(req.msg.ToString());
            int CommissionId = prams.GetInt("CommissionId", 0);
            if (CommissionId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = userModule.SetGetHpDistrIbutorEnabled(CommissionId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取和平分销是否启用
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetHpDistributorIsEnabled()
        {
            var req = RequestParm;

            int enabled = userModule.GetHpDistributorIsEnabled(req.TenantId, req.MallBaseId);
            return ApiResult.Success("", enabled);
        }

        /// <summary>
        /// 删除和平分销
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelHpDistributorInfo()
        {
            var req = RequestParm;
            JObject prams = JObject.Parse(req.msg.ToString());
            int CommissionId = prams.GetInt("CommissionId", 0);
            if (CommissionId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            bool flag = userModule.DelHpDistributorInfo(CommissionId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取和平分销用户信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetHpUserDistributorInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int UserId = parms.GetInt("UserId", 0);
            if (UserId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

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

        /// <summary>
        /// 获取商品建议价格
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetHpGoodsSuggestPrice()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string CategoryIds = parms.GetStringValue("CategoryIds");
            decimal CostPrice = parms.GetDecimal("CostPrice");
            if (CostPrice <= 0)
            {
                return ApiResult.ParamIsNull("请传递成本价格");
            }

            var obj = userModule.GetHpGoodsSuggestPrice(CategoryIds, CostPrice, req.TenantId, req.MallBaseId);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 获取和平分销在商品中使用详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetHpDistributorGoodsInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string CategoryIds = parms.GetStringValue("CategoryIds");
            decimal CostPrice = parms.GetDecimal("CostPrice");
            if (CostPrice <= 0)
            {
                return ApiResult.ParamIsNull("请传递成本价格");
            }

            var obj = userModule.GetHpDistributorGoodsInfo(CategoryIds, CostPrice, req.TenantId, req.MallBaseId);
            return ApiResult.Success("", obj);
        }

        #endregion

        #region 粉象返佣

        /// <summary>
        /// 获取粉象分销等级信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFXDistributorGradePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Distributor_FXGrade_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_FXGrade_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetFXDistributorGradePageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Grade,
                x.GradeName,
                x.IsGuest,
                x.CommissionRatio,
                x.SiblingRatio,
                x.SiblingRebatesNum,
                x.IsCanBuy,
                x.BuyMoney,
                x.Year,
                x.IsUpgrade,
                x.UpgradeNum,
                x.DecimalType,
                x.UpgradeId,
                x.Description,
                x.Icon,
                x.CommissionType,
                UpdateDate = x.UpdateDate.HasValue ? x.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取粉象分销等级信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFXDistributorGradeList()
        {
            var parms = RequestParm;
            RB_Distributor_FXGrade_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_FXGrade_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetFXDistributorGradeList(demodel);
            return ApiResult.Success("", list.Select(x => new
            {
                x.Id,
                x.Grade,
                x.GradeName,
                x.IsGuest
            }));
        }

        /// <summary>
        /// 新增修改等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetFXDistributorGradeInfo()
        {
            var req = RequestParm;
            RB_Distributor_FXGrade_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_FXGrade_Extend>(req.msg.ToString());
            if (string.IsNullOrEmpty(demodel.GradeName))
            {
                return ApiResult.ParamIsNull("等级名称");
            }
            if ((demodel.Grade ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请选择等级");
            }
            if ((demodel.CommissionRatio ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递返佣比例");
            }
            if ((demodel.SiblingRatio ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递同级返佣比例");
            }
            //验证等级是否重复
            if (userModule.ValidateFXGrade(demodel.Id, demodel.Grade, req.TenantId, req.MallBaseId))
            {
                return ApiResult.ParamIsNull("等级已存在，请核实后再试");
            }

            if ((demodel.IsUpgrade ?? 2) == 1)
            {
                if ((demodel.UpgradeNum ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请输入所需下线数量");
                }
                if ((demodel.UpgradeId ?? 0) <= 0)
                {
                    return ApiResult.ParamIsNull("请选择所需下线等级");
                }
            }

            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.Status = 0;
            demodel.IsGuest ??= 2;
            demodel.SiblingRebatesNum ??= 1;
            demodel.IsCanBuy ??= 2;
            demodel.BuyMoney ??= 0;
            demodel.Year ??= 1;
            demodel.IsUpgrade ??= 0;
            demodel.UpgradeNum ??= 0;
            demodel.UpgradeId ??= 0;
            demodel.DecimalType ??= 1;
            demodel.Description ??= "";
            demodel.CreateDate = DateTime.Now;
            demodel.UpdateDate = DateTime.Now;
            bool flag = userModule.SetFXDistributorGradeInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelFXDistributorGradeInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GradeId = parms.GetInt("GradeId", 0);
            if (GradeId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            //验证  有用户在使用该等级  不能删除

            bool flag = userModule.DelFXDistributorGradeInfo(GradeId, req.TenantId, req.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取粉象粉象视图查看
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFXDistributorGradeView()
        {
            var req = RequestParm;
            return userModule.GetFXDistributorGradeView(req.TenantId, req.MallBaseId);
        }

        /// <summary>
        /// 获取是否启用粉象返佣
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetIsEnableFXDistributorGrade()
        {
            var requestParm = RequestParm;
            var model = userModule.GetDistributorBasicsInfo(requestParm.uid, requestParm.MallBaseId);

            return ApiResult.Success("", model?.IsEnableFXGrade ?? 2);
        }

        #endregion

        #region 后台获取小程序码

        /// <summary>
        /// 获取微信小程序码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetWeiXinQRCodeForHT()
        {
            var req = RequestParm;
            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, req.MallBaseId);
            return ApiResult.Success("", base64Img);
        }

        #endregion

        #region 推荐返佣账单
        /// <summary>
        /// 获取账单列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetRecommendOrdersBillPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Distributor_Bill_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Bill_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.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.BillState,
                x.Money,
                x.Periods,
                x.Remark,
                x.SupplierId,
                x.SupplierName,
                x.UserId,
                x.UserName,
                UpdateDate = x.UpdateDate.HasValue ? x.UpdateDate.Value.ToString("yyyy-MM-dd") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 新增账单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetRecommendOrdersBillInfo()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            string IntroductionIds = parms.GetStringValue("IntroductionIds");
            int UserId = parms.GetInt("UserId", 0);
            int SupplierId = parms.GetInt("SupplierId", 0);
            if (string.IsNullOrEmpty(IntroductionIds))
            {
                return ApiResult.ParamIsNull("请选择返佣订单");
            }
            List<int> IntroductionIdList = JsonConvert.DeserializeObject<List<int>>(IntroductionIds);
            if (!IntroductionIdList.Any())
            {
                return ApiResult.ParamIsNull("请选择返佣订单");
            }
            if (UserId <= 0)
            {
                return ApiResult.ParamIsNull("请选择用户");
            }

            bool flag = userModule.SetRecommendOrdersBillInfo(IntroductionIdList, UserId, SupplierId, req.TenantId, req.MallBaseId, req.EmpId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 账单取消
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult CancalRecommendOrdersBill()
        {
            var req = RequestParm;
            var parms = JObject.Parse(req.msg.ToString());
            int BillId = parms.GetInt("BillId", 0);
            if (BillId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            bool flag = userModule.CancalRecommendOrdersBill(BillId, req.TenantId, req.MallBaseId, req.EmpId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 修改备注
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetRecommendOrdersBillRemark()
        {
            var req = RequestParm;
            var parms = JObject.Parse(req.msg.ToString());
            int BillId = parms.GetInt("BillId", 0);
            string Remark = parms.GetStringValue("Remark");
            if (BillId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            bool flag = userModule.SetRecommendOrdersBillRemark(BillId, Remark);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 账单打款
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetRecommendOrdersBillRemit()
        {
            var req = RequestParm;
            var parms = JObject.Parse(req.msg.ToString());
            int BillId = parms.GetInt("BillId", 0);
            if (BillId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var bmodel = userModule.GetBillModel(BillId);
            if (bmodel == null) { return ApiResult.Failed("账单不存在"); }
            if (bmodel.BillState != 1) { return ApiResult.Failed("账单状态不正确"); }

            int IsNormalServer = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("IsNormalServer").Value);
            if (IsNormalServer == 1)
            {
                var mallModel = userModule.GetMiniProgramExtend(req.MallBaseId);
                var umodel = userModule.GetMemberUserInfo(bmodel.UserId ?? 0);
                var flag = App_Code.PayUtil.GetTransfersOrder((bmodel.Periods ?? "") + bmodel.Id, bmodel.Money ?? 0, (bmodel.UserId ?? 0).ToString(), umodel.OpenId, mallModel, _accessor, "赞羊供应商佣金打款");
                if (flag)
                {
                    string msg = userModule.SetRecommendOrdersBillRemit(BillId, req.TenantId, req.MallBaseId, req.EmpId);
                    if (msg != "")
                    {
                        LogHelper.Write("企业付款失败 账单BillId:" + BillId);
                    }

                    new MiniProgramMsgModule().SendWithdrawSucceedMsg(req.TenantId, req.MallBaseId, umodel.OpenId, (bmodel.Money ?? 0).ToString(), "0", "自动打款", "已发放供应商佣金，请注意查收");
                    return ApiResult.Success();
                }
                else
                {
                    LogHelper.Write("企业付款失败 账单BillId:" + BillId);
                    return ApiResult.Failed("支付失败");
                }
            }
            else
            {
                string msg = userModule.SetRecommendOrdersBillRemit(BillId, req.TenantId, req.MallBaseId, req.EmpId);
                if (msg == "")
                {
                    return ApiResult.Success();
                }
                else
                {
                    return ApiResult.Failed(msg);
                }
            }
        }

        /// <summary>
        /// 获取账单明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetRecommendOrdersBillDetailList()
        {
            var parms = RequestParm;
            RB_Distributor_BillDetail_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_BillDetail_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            if ((demodel.BillId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递账单id");
            }
            var Robj = userModule.GetRecommendOrdersBillDetailList(demodel);
            return ApiResult.Success("", Robj);
        }
        #endregion

        #region 粉象返佣金额设置

        /// <summary>
        /// 初始化 赠送粉象vip返佣
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult InitializeFXVIPCommission()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int OrderId = parms.GetInt("OrderId", 0);
            if (OrderId <= 0)
            {
                return ApiResult.ParamIsNull("请传递参数");
            }
            new UserCommonModule().TestFxGradeCommission(OrderId);

            return ApiResult.Success();
        }

        /// <summary>
        /// 获取粉象分销返佣信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFXFxCommissionList()
        {
            var parms = RequestParm;
            RB_Distributor_FXGrade_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_FXGrade_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = userModule.GetFXDistributorGradeList(demodel).Where(x => x.IsGuest > 1);
            //获取返佣价格设置
            var listCommission = userModule.GetFXCommissionList(new RB_Distributor_FXCommission_Extend { TenantId = Convert.ToInt32(parms.uid), MallBaseId = parms.MallBaseId });
            List<RB_Distributor_FXGrade_Extend> titleList = new List<RB_Distributor_FXGrade_Extend>();

            foreach (var item in list)
            {
                item.FXCommissionList = new List<RB_Distributor_FXCommission_Extend>();
                var nowList = listCommission.Where(x => x.FXGradeId == item.Id);

                RB_Distributor_FXGrade_Extend titleModel = new RB_Distributor_FXGrade_Extend
                {
                    GradeName = item.IsGuest == 3 ? "直接" + item.GradeName : item.GradeName,
                };
                titleList.Add(titleModel);

                if (item.IsGuest == 3)
                {
                    titleModel = new RB_Distributor_FXGrade_Extend
                    {
                        GradeName = "间接" + item.GradeName,
                    };
                    titleList.Add(titleModel);
                }

                foreach (var commissionItem in list)
                {
                    if (nowList.Any(x => x.CommissionGradeId == commissionItem.Id && x.FXGradeId == item.Id))
                    {
                        var nowCommissionList = nowList.Where(x => x.CommissionGradeId == commissionItem.Id && x.FXGradeId == item.Id);
                        nowCommissionList.ToList().ForEach(x => x.GradeName = (commissionItem.IsGuest == 3 ? "直接" + commissionItem.GradeName : commissionItem.GradeName));
                        item.FXCommissionList.AddRange(nowCommissionList);
                        if (commissionItem.IsGuest == 3 && nowCommissionList.Count() < 2)
                        {
                            if (nowCommissionList.FirstOrDefault().GradeType == 1)
                            {
                                RB_Distributor_FXCommission_Extend model = new RB_Distributor_FXCommission_Extend
                                {
                                    ID = 0,
                                    FXGradeId = item.Id,
                                    CommissionGradeId = commissionItem.Id,
                                    GradeType = 2,
                                    CommissionPrice = 0,
                                    Status = 0,
                                    GradeName = "间接" + commissionItem.GradeName,
                                    MallBaseId = item.MallBaseId,
                                    TenantId = item.TenantId,
                                };
                                item.FXCommissionList.Add(model);
                            }
                            else
                            {
                                RB_Distributor_FXCommission_Extend model = new RB_Distributor_FXCommission_Extend
                                {
                                    ID = 0,
                                    FXGradeId = item.Id,
                                    CommissionGradeId = commissionItem.Id,
                                    GradeType = 1,
                                    CommissionPrice = 0,
                                    Status = 0,
                                    GradeName = "间接" + commissionItem.GradeName,
                                    MallBaseId = item.MallBaseId,
                                    TenantId = item.TenantId,
                                };
                                item.FXCommissionList.Add(model);
                            }
                        }
                    }
                    else
                    {

                        RB_Distributor_FXCommission_Extend model = new RB_Distributor_FXCommission_Extend
                        {

                            ID = 0,
                            FXGradeId = item.Id,
                            CommissionGradeId = commissionItem.Id,
                            GradeType = 1,
                            CommissionPrice = 0,
                            Status = 0,
                            GradeName = commissionItem.IsGuest == 3 ? "直接" + commissionItem.GradeName : commissionItem.GradeName,
                            MallBaseId = item.MallBaseId,
                            TenantId = item.TenantId,
                        };
                        item.FXCommissionList.Add(model);
                        if (commissionItem.IsGuest == 3)
                        {
                            model = new RB_Distributor_FXCommission_Extend
                            {
                                ID = 0,
                                FXGradeId = item.Id,
                                CommissionGradeId = commissionItem.Id,
                                GradeType = 2,
                                CommissionPrice = 0,
                                Status = 0,
                                GradeName = "间接" + commissionItem.GradeName,
                                MallBaseId = item.MallBaseId,
                                TenantId = item.TenantId,
                            };
                            item.FXCommissionList.Add(model);
                        }
                    }
                }
            }
            var result = new
            {
                resultList = list.Select(x => new
                {
                    x.Id,
                    x.GradeName,
                    x.FXCommissionList,
                    x.Grade,

                }),
                titleList = titleList.Select(x => new { x.GradeName })
            };

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

        /// <summary>
        /// 新增修改等级
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetFXFxCommissionInfo()
        {
            var req = RequestParm;
            List<RB_Distributor_FXGrade_Extend> demodel = JsonConvert.DeserializeObject<List<RB_Distributor_FXGrade_Extend>>(req.msg.ToString());

            List<RB_Distributor_FXCommission_Extend> list = new List<RB_Distributor_FXCommission_Extend>();
            foreach (var item in demodel)
            {
                list.AddRange(item.FXCommissionList);
            }
            if (list.Any(x => x.CommissionPrice < 0))
            {
                return ApiResult.Failed("返佣价格不能小于0");
            }
            bool flag = userModule.AddOrUpdateFxCommission(list);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        #endregion

        #region 微店基础设置获取分销等级
        [HttpPost]
        public ApiResult GetGradeByType()
        {
            var re = RequestParm;
            var parms = JObject.Parse(re.msg.ToString());
            int GradeType = parms.GetInt("GradeType", 0);
            if (GradeType == 1)
            {
                RB_Distributor_Grade_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_Grade_Extend>(re.msg.ToString());

                demodel.TenantId = Convert.ToInt32(re.uid);
                demodel.MallBaseId = re.MallBaseId;
                var list = userModule.GetDistributorGradeDropdownList(demodel);

                return ApiResult.Success("", list.Select(x => new
                {
                    x.Id,
                    x.Name,
                    x.Grade
                }));
            }
            else if (GradeType == 2)
            {
                RB_Distributor_FXGrade_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_FXGrade_Extend>(re.msg.ToString());

                demodel.TenantId = Convert.ToInt32(re.uid);
                demodel.MallBaseId = re.MallBaseId;
                var list = userModule.GetFXDistributorGradeList(demodel);

                return ApiResult.Success("", list.Select(x => new
                {
                    x.Id,
                    Name = x.GradeName,
                    x.Grade
                }));
            }
            else
            {
                List<RB_Distributor_Grade_Extend> list = new List<RB_Distributor_Grade_Extend>();
                return ApiResult.Success("", list.Select(x => new
                {
                    x.Id,
                    x.Name,
                    x.Grade
                }));
            }
        }
        #endregion

        #region 获取用户列表
        [HttpPost]
        [AllowAnonymous] [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetMemberUserListExt()
        {
            var re = RequestParm;
            var parms = JObject.Parse(re.msg.ToString());
            RB_Member_User_Extend query = new RB_Member_User_Extend()
            {
                Name = parms.GetStringValue("Name"),
            };
            query.TenantId = Convert.ToInt32(re.uid);
            query.MallBaseId = re.MallBaseId;
            var list = userModule.GetMemberUserListExtModule(query);
            return ApiResult.Success(data: list.Select(qitem => new
            {
                qitem.Id,
                qitem.Name,
                qitem.ShopId,
                qitem.ShopName
            }));
        }
        #endregion

        /// <summary>
        /// 获取收货地址列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] [RateValve(Policy = Policy.Ip, Limit = 20, Duration = 60)]
        public ApiResult GetShippingAddressList()
        {
            var req = RequestParm;
            RB_Member_ShippingAddress_Extend demodel = JsonConvert.DeserializeObject<RB_Member_ShippingAddress_Extend>(req.msg.ToString());
            JObject parms = JObject.Parse(req.msg.ToString());
            demodel.TenantId = req.TenantId;
            demodel.MallBaseId = req.MallBaseId;
            demodel.UserId = req.UserId;
            //HK2020-09-09新增用户Id
            if (parms.GetInt("NewUserId") > 0)
            {
                demodel.UserId = parms.GetInt("NewUserId");
            }
            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") : ""
            }));
        }


        #region 用户分组管理
        /// <summary>
        /// 获取用户分组分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberGroupPage()
        {
            var parms = RequestParm;
            JObject param = JObject.Parse(parms.msg.ToString());
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Member_Group_Extend demodel = new RB_Member_Group_Extend()
            {
                GroupName = param.GetStringValue("GroupName"),
            };
            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = memberGroupModule.GetMemberGroupPageModule(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            List<object> result = new List<object>();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    result.Add(new
                    {
                         item.GroupId,
                         item.GroupName,
                         item.LookGroupIds,
                         item.GroupIdList,
                         item.LookGroupList,
                         item.IsDefault,
                         CreateDate = Common.ConvertHelper.FormatTime(item.CreateDate),
                    });
                }
            }
            pagelist.pageData = result;
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取用户分组下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberGroupList()
        {
            var parms = RequestParm;
            JObject param = JObject.Parse(parms.msg.ToString());
            RB_Member_Group_Extend demodel = new RB_Member_Group_Extend()
            {
                GroupName = param.GetStringValue("GroupName"),
            };
            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = memberGroupModule.GetMemberGroupListModule(demodel);
            return ApiResult.Success("", list);
        }


        /// <summary>
        /// 获取用户分组信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetMemberGroup()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            RB_Member_Group_Extend model = new RB_Member_Group_Extend()
            {
                GroupId= parms.GetInt("GroupId", 0),
                GroupName=parms.GetStringValue("GroupName"),
            };
            var GroupIdList = new List<int>();
            if (!string.IsNullOrEmpty(parms.GetStringValue("GroupIdList")))
            {
                GroupIdList = JsonHelper.DeserializeObject<List<int>>(parms.GetStringValue("GroupIdList"));
            }
            model.LookGroupIds = string.Join(",", GroupIdList);
            model.TenantId = requestParm.TenantId;
            model.MallBaseId = requestParm.MallBaseId;
            model.Status = Common.Enum.DateStateEnum.Normal;
            model.CreateBy = requestParm.TenantId;
            model.CreateDate = DateTime.Now;
            model.UpdateBy = requestParm.TenantId;
            model.UpdateDate = DateTime.Now;
            var flag = memberGroupModule.SetMemberGroupModule(model);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 获取用户分组信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMemberGroup()
        {
            var parms = JObject.Parse(RequestParm.msg.ToString());
            int GroupId = parms.GetInt("GroupId", 0);
            var model = memberGroupModule.GetMemberGroupModule(GroupId);
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 设置默认分组
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDefaultGroup()
        {
            var parms = JObject.Parse(RequestParm.msg.ToString());
            int GroupId = parms.GetInt("GroupId", 0);
            var model = memberGroupModule.SetDefaultGroupModule(GroupId, RequestParm.MallBaseId);
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 删除用户分组信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DeleteMemberGroup()
        {
            var parms = JObject.Parse(RequestParm.msg.ToString());
            int GroupId = parms.GetInt("GroupId", 0);
            var flag = memberGroupModule.RemoveMemberGroupModule(GroupId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
        #endregion
    }
}