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 Mall.Model.Extend.Product;
using Mall.Model.Extend.MarketingCenter;
using Mall.Model.Entity.User;
using NPOI.SS.Formula.Functions;

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

        private readonly UserModule userModule = new UserModule();
        private readonly Module.MarketingCenter.CouponModule couponModule = new Module.MarketingCenter.CouponModule();
        #region 收货地址

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

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

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

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

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

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

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

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

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

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

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

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

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

        #endregion

        #region 收藏商品

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

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

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

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

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

        #endregion

        #region 分销中心

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return ApiResult.Success("", pageModel);
        }
        //分销订单  提现明细  我的团队

        #endregion

        #region 会员中心

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

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

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

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

        #endregion

        #region 我的足迹

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

            demodel.UserId = userInfo.UserId;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = userModule.GetUserFootMarkPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.GoodsId,
                x.GoodsName,
                x.GoodsImgPath,
                x.Price,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd") : ""
            });

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

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

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

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

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

        #endregion

        #region 个人中心

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

        #endregion        

        #region 优惠券

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



        /// <summary>
        /// 领取优惠券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GrantCoupon()
        {
            var parms = RequestParm;
            var userInfo = AppletUserInfo;
            var query = JsonConvert.DeserializeObject<RB_Member_DiscountCoupon_Extend>(RequestParm.msg.ToString());
            query.TenantId = userInfo.TenantId;
            query.MallBaseId = userInfo.MallBaseId;
            query.UserId = userInfo.UserId;
            if (query == null)
            {
                return ApiResult.Failed("请传入卡券信息");
            }
            else
            {
                var oldLogisticsModel = couponModule.GetDiscountCouponList(new RB_DiscountCoupon_Extend { TenantId = query.TenantId, MallBaseId = query.MallBaseId, ID = query.CouponId }).FirstOrDefault();
                if (oldLogisticsModel == null || oldLogisticsModel.ID == 0)
                {
                    return ApiResult.Failed("优惠券信息不存在，请核实后再操作");
                }
                if (oldLogisticsModel.TotalNum != -1)//判断优惠券剩余数量是够足够
                {
                    if (oldLogisticsModel.TotalNum < 1)
                    {
                        return ApiResult.Failed("优惠券已领完");
                    }
                }
                //判断优惠券是否已领取
                var receiveList = couponModule.GetMemberDiscountCouponList(query);
                if (receiveList != null && receiveList.Any())
                {
                    return ApiResult.Failed("您已领取优惠券");
                }


                if (oldLogisticsModel.EndDate.Value < System.DateTime.Now)
                {
                    return ApiResult.Failed("优惠券时间已过期");
                }
                var allMemberInfo = userModule.GetMemberUserInfo(userInfo.UserId);
                //判断优惠券是否有等级限制
                if (oldLogisticsModel.OnlyMember == 1)
                {
                    if (!string.IsNullOrWhiteSpace(oldLogisticsModel.MemberLevel))
                    {
                        string[] allLevel = oldLogisticsModel.MemberLevel.Split(',');
                        if (allLevel.Where(x => x == allMemberInfo.MemberGrade.ToString()).Count() == 0)
                        {
                            return ApiResult.Failed("会员等级不符合");
                        }
                    }
                }


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


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

        #endregion

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

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

        #region 获取小程序码

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

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

        #endregion

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

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

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

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

            }

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