public ActionResult UserApplyForScore(string address, int score, int?adds_id)
 {
     if (UserInfo.user.usable_score >= score)
     {
         var na = new user_score_record();
         na.id                 = Guid.NewGuid();
         na.user_id            = UserInfo.id;
         na.score              = score;
         na.rollout_address_id = adds_id != null ? adds_id : SaveAddress(address, UserInfo);
         na.type               = (int)Score_type.提现;
         na.state              = (int)User_score_record_state.等待处理;
         na.source_name        = $"{UserInfo.nickname}发起了提现了申请";
         na.remark             = ((int)Score_source_remark.用户提现).ToString();
         na.add_time           = DateTime.Now;
         try
         {
             var res = User_score_recordService.AddEntity(na);
             CacheHelper.RemoveCache($"User_score_record_id={UserInfo.id}");
             return(Json(SysEnum.成功, "提交申请成功"));
         }
         catch (Exception)
         {
             return(Json(SysEnum.失败, "提交申请失败"));
         }
     }
     return(Json(SysEnum.失败, "提现积分不够"));
 }
        /// <summary>
        /// 订阅(关注)事件
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            var accessToken = Senparc.Weixin.MP.Containers.AccessTokenContainer.TryGetAccessToken(appId, appSecret);
            var openId      = requestMessage.FromUserName;//获取OpenId
            var userInfo    = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(appId, openId, Language.zh_CN);
            var temp        = wx_userService.LoadEntities(u => u.gzh_openid == openId).FirstOrDefault();

            if (temp != null)
            {
                temp.state    = (int)WXUserState.已关注;
                temp.add_time = DateTime.Now;
                wx_userService.EditEntity(temp);
            }
            else
            {
                //新用户
                var user = new user();
                user.pid   = 0;
                user.name  = userInfo.nickname;
                user.sex   = userInfo.sex;
                user.state = (int)User_state.正常;
                user.isbuy = (int)Isbuy.未购买;
                //首次关注赠送积分
                var config_ruleItem = Config_ruleService.LoadEntities(n => n.name == "首次关注" && n.state == (int)State.可用).FirstOrDefault();
                if (config_ruleItem != null)
                {
                    var usr = new user_score_record();
                    usr.id    = Guid.NewGuid();
                    usr.score = config_ruleItem.value != null?Convert.ToDecimal(config_ruleItem.value) : 0;

                    usr.type           = (int)Score_type.收益;
                    usr.state          = (int)User_score_record_state.已完成;
                    usr.source_name    = "首次关注系统赠送";
                    usr.add_time       = DateTime.Now;
                    usr.remark         = ((int)Score_source_remark.系统赠送).ToString();
                    user.total_score  += usr.score;
                    user.usable_score += user.total_score;
                    user.user_score_record.Add(usr);
                }
                var newUser = new wx_user()
                {
                    city             = userInfo.city,
                    country          = userInfo.country,
                    wx_head_protrait = userInfo.headimgurl,
                    nickname         = userInfo.nickname,
                    gzh_openid       = userInfo.openid,
                    province         = userInfo.province,
                    sex      = userInfo.sex,
                    add_time = DateTime.Now,
                    unionid  = userInfo.unionid,
                    state    = (int)WXUserState.已关注,                 //已关注
                    user     = user,
                };
                wx_userService.AddEntity(newUser);
            }
            var responseMessage = base.CreateResponseMessage <ResponseMessageText>();

            responseMessage.Content = userInfo.nickname + ",欢迎您关注我们~";
            return(responseMessage);
        }
        /// <summary>
        /// 给上级添加积分记录
        /// </summary>
        /// <returns></returns>
        private bool AddUserScore(int pid, order order)
        {
            var first   = UserService.LoadEntities(n => n.id == pid).FirstOrDefault();
            var res     = new List <user_score_record>();
            var useList = new List <user>();

            if (first != null)
            {
                var f = new user_score_record();
                f.add_time    = DateTime.Now;
                f.user_id     = first.id;
                f.order_id    = order.id;
                f.remark      = ((int)Score_source_remark.一级用户购买赠送).ToString();
                f.source_id   = order.user_id;
                f.score       = order.product.first_level_referral_bonuses * order.count;
                f.source_name = $"一级用户{order.user.name}在{DateTime.Now.ToString()}购买{order.product.name}返回收益";
                f.type        = (int)Score_type.收益;
                f.id          = Guid.NewGuid();
                f.state       = (int)User_score_record_state.已完成;
                res.Add(f);

                first.total_score  += f.score;
                first.usable_score += f.score;
                useList.Add(first);

                var second = first.pid != 0 ? UserService.LoadEntities(n => n.id == first.pid).FirstOrDefault() : null;
                if (second != null)
                {
                    var s = new user_score_record();
                    s.add_time    = DateTime.Now;
                    s.user_id     = second.id;
                    s.order_id    = order.id;
                    s.remark      = ((int)Score_source_remark.二级用户购买赠送).ToString();
                    s.source_id   = order.user_id;
                    s.score       = order.product.second_level_referral_bonuses * order.count;
                    s.source_name = $"二级用户{order.user.name}在{DateTime.Now.ToString()}购买{order.product.name}返回收益";
                    s.type        = (int)Score_type.收益;
                    s.id          = Guid.NewGuid();
                    s.state       = (int)User_score_record_state.已完成;
                    res.Add(s);

                    second.total_score  += s.score;
                    second.usable_score += s.score;
                    useList.Add(second);
                }
                User_score_recordService.AddEnties(res);
                UserService.EditEntities(useList);
                return(true);
            }
            return(false);
        }
        /// <summary>
        /// 用户提现成功后
        /// </summary>
        /// <param name="id">用户id</param>
        /// <param name="sid"></param>
        /// <returns></returns>
        public ActionResult AfterApplySuccess(int id, Guid sid)
        {
            var userItem = UserService.LoadEntities(n => n.id == id).FirstOrDefault();
            var config   = Config_ruleService.LoadEntities(n => n.name == "提现费用").FirstOrDefault();

            var us = User_score_recordService.LoadEntities(n => n.id == sid).FirstOrDefault();

            if (us != null && us.score > 0)
            {
                userItem.usable_score -= us.score;
            }
            if (config != null)
            {
                Decimal.TryParse(config.value, out decimal score);
                if (userItem != null)
                {
                    var nUsr = new user_score_record();
                    nUsr.id          = Guid.NewGuid();
                    nUsr.user_id     = id;
                    nUsr.type        = (int)Score_type.系统扣除;
                    nUsr.score       = score;
                    nUsr.state       = (int)User_score_record_state.已完成;
                    nUsr.source_name = $"{userItem.name}提现扣除积分{score}";
                    nUsr.add_time    = DateTime.Now;
                    nUsr.remark      = ((int)Score_source_remark.系统扣除积分).ToString();

                    //userItem.total_score -= nUsr.score;
                    userItem.usable_score -= nUsr.score;

                    userItem.user_score_record.Add(nUsr);

                    if (UserService.EditEntity(userItem))
                    {
                        CacheHelper.RemoveCache("all_user_list");
                        CacheHelper.RemoveCache($"usr_type={nUsr.type}");
                        SaveSyslog($"添加了一条用户{userItem.id}的积分记录", SysLogType.后台日志, nowManager.name);
                        return(Json(SysEnum.成功, "添加扣除积分记录成功"));
                    }
                    return(Json(SysEnum.失败, "添加用户总积分失败"));
                }
                return(Json(SysEnum.失败, "没有找到对象规则"));
            }
            return(Json(SysEnum.失败, "没有提现费用规则"));
        }
        /// <summary>
        /// 添加用户积分记录
        /// </summary>
        /// <returns></returns>
        public ActionResult AddUserScoreRecord()
        {
            var data     = Request["data"];
            var usrData  = SerializeHelper.SerializeToObject <dynamic>(data);
            int user_id  = usrData.user_id;
            var userItem = UserService.LoadEntities(n => n.id == user_id).FirstOrDefault();

            if (userItem != null)
            {
                int remark = usrData.remark;
                var nUsr   = new user_score_record();
                nUsr.id          = Guid.NewGuid();
                nUsr.user_id     = user_id;
                nUsr.type        = usrData.type;
                nUsr.score       = usrData.score;
                nUsr.state       = (int)User_score_record_state.已完成;
                nUsr.source_name = $"管理员{nowManager.name}执行了{Enum.GetName(typeof(Score_source_remark), remark)}选项,原因:{usrData.source_name}";
                nUsr.add_time    = DateTime.Now;
                nUsr.remark      = usrData.remark;
                if (nUsr.remark == ((int)Score_source_remark.系统扣除积分).ToString())
                {
                    userItem.total_score  -= nUsr.score;
                    userItem.usable_score -= nUsr.score;
                }
                else
                {
                    userItem.total_score  += nUsr.score;
                    userItem.usable_score += nUsr.score;
                }
                userItem.user_score_record.Add(nUsr);
                if (UserService.EditEntity(userItem))
                {
                    CacheHelper.RemoveCache("all_user_list");
                    CacheHelper.RemoveCache($"user_id={user_id}_srList");
                    SaveSyslog($"添加了一条用户{userItem.id}的积分记录", SysLogType.后台日志, nowManager.name);
                    return(Json(SysEnum.成功, usrData.type, "添加积分记录成功"));
                }
                return(Json(SysEnum.失败, "添加用户总积分失败"));
            }
            return(Json(SysEnum.失败, "没有找到该对象"));
        }
        private Tuple <List <user_score_record>, Dictionary <user, decimal> > AddScoreRecord(user user, user puser, user ppuser, product pro, int h, DateTime date)
        {
            var     res        = new List <user_score_record>();
            var     itms       = new List <user>();
            var     userR      = new user_score_record();
            var     res_items  = new Dictionary <user, decimal>();
            decimal totalscore = pro.Calculate_the_force * h;
            decimal ps         = puser == null ? 0 : (totalscore * pro.first_level_earnings_bonuses) / 100;
            decimal pps        = ppuser == null ? 0 : (totalscore * pro.second_level_earnings_bonuses) / 100;

            userR.id      = Guid.NewGuid();
            userR.user_id = user.id;
            //userR.score = totalscore - ps - pps;//从用户收益扣除
            userR.score       = totalscore;      //从系统奖励
            userR.type        = (int)Score_type.收益;
            userR.state       = (int)User_score_record_state.已完成;
            userR.source_name = $"{pro.name}在{date.AddDays(-1).ToShortDateString()}的收益";
            userR.add_time    = date;
            userR.remark      = ((int)Score_source_remark.产品直接收益).ToString();
            res.Add(userR);

            //user.total_score += userR.score;
            //user.usable_score += userR.score;
            //itms.Add(user);
            res_items.Add(user, userR.score);

            if (ps > 0)
            {
                var userPR = new user_score_record();
                userPR.id          = Guid.NewGuid();
                userPR.user_id     = puser.id;
                userPR.type        = (int)Score_type.收益;
                userPR.score       = ps;
                userPR.state       = (int)User_score_record_state.已完成;
                userPR.source_name = $"一级用户{user.name}的{pro.name}在{date.AddDays(-1).ToShortDateString()}的返回的收益";
                userPR.add_time    = date;
                userPR.source_id   = user.id;
                userPR.remark      = ((int)Score_source_remark.一级用户产品间接收益).ToString();
                res.Add(userPR);
                //puser.total_score += userPR.score;
                //puser.usable_score += userPR.score;
                //itms.Add(user);
                res_items.Add(puser, userPR.score);
            }
            if (pps > 0)
            {
                var userPPR = new user_score_record();
                userPPR.id          = Guid.NewGuid();
                userPPR.user_id     = ppuser.id;
                userPPR.type        = (int)Score_type.收益;
                userPPR.score       = pps;
                userPPR.state       = (int)User_score_record_state.已完成;
                userPPR.source_name = $"二级用户{user.name}的{pro.name}在{date.AddDays(-1).ToShortDateString()}的返回的收益";
                userPPR.remark      = ((int)Score_source_remark.二级用户产品间接收益).ToString();
                userPPR.add_time    = date;
                userPPR.source_id   = user.id;
                res.Add(userPPR);

                //ppuser.total_score += userPPR.score;
                //ppuser.usable_score += userPPR.score;
                //itms.Add(user);
                res_items.Add(ppuser, userPPR.score);
            }
            return(new Tuple <List <user_score_record>, Dictionary <user, decimal> >(res, res_items));
        }
        /// <summary>
        /// 公众号授权回调
        /// </summary>
        /// <param name="code">The code.</param>
        /// <param name="state">The state.</param>
        /// <param name="goUrl">要跳转的url地址</param>
        /// <returns>跳转的url地址会带上Token</returns>
        public ActionResult UserInfoCallback(string code, string state, string goUrl)
        {
            goUrl = Common.EncryptHelper.Decrypt(goUrl);
            var    temp   = Request;
            string parms  = string.Empty;
            string strpid = string.Empty;

            if (goUrl.IndexOf('?') > -1)
            {
                parms = goUrl.Substring(goUrl.IndexOf('?'));
                if (parms.Contains("pid"))
                {
                    strpid = parms.Substring(parms.IndexOf("pid")).Split('=')[1];
                }
            }
            //var strpid = goUrl.Substring(goUrl.IndexOf('?'), goUrl.Length).Split('=')[1];

            if (string.IsNullOrEmpty(code))
            {
                return(Content("您拒绝了授权!"));
            }

            OAuthAccessTokenResult result = null;
            string token = string.Empty;

            //通过,用code换取access_token
            try
            {
                result = OAuthApi.GetAccessToken(appId, secret, code);
                token  = Common.EncryptHelper.Encrypt(string.Format("{0}|{1}|{2}", result.openid, Request.UserHostAddress, RequestCategory.微信公众号));
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("40163"))
                {
                    return(Redirect(goUrl));
                }
                return(Content(ex.Message));
            }

            if (result.errcode != ReturnCode.请求成功)
            {
                return(Redirect(goUrl));
            }
            try
            {
                var wxUser   = OAuthApi.GetUserInfo(result.access_token, result.openid);
                var tempUser = Wx_userService.LoadEntities(u => u.unionid == wxUser.unionid || u.gzh_openid == wxUser.openid).FirstOrDefault();
                if (!int.TryParse(strpid, out int pid))
                {
                    pid = 0;
                }

                if (tempUser != null)
                {
                    if (tempUser.state == (int)WXUserState.取消关注)
                    {
                        tempUser.state    = (int)WXUserState.未关注;
                        tempUser.add_time = DateTime.Now;
                    }
                    //if (tempUser.unsubscribe_time==null||tempUser.unsubscribe_time<=DateTime.Now.AddDays(-7))
                    if (true)
                    {
                        if (tempUser.user == null)
                        {
                            //新用户
                            var user = new user();
                            user.pid   = pid;
                            user.name  = wxUser.nickname;
                            user.sex   = wxUser.sex;
                            user.state = (int)User_state.正常;
                            user.isbuy = (int)Isbuy.未购买;
                            //首次关注赠送积分
                            var config_ruleItem = Config_ruleService.LoadEntities(n => n.name == "首次关注" && n.state == (int)State.可用).FirstOrDefault();
                            if (config_ruleItem != null)
                            {
                                var usr = new user_score_record();
                                usr.id    = Guid.NewGuid();
                                usr.score = config_ruleItem.value != null?Convert.ToDecimal(config_ruleItem.value) : 0;

                                usr.type           = (int)Score_type.收益;
                                usr.state          = (int)User_score_record_state.已完成;
                                usr.source_name    = "首次关注系统赠送";
                                usr.add_time       = DateTime.Now;
                                usr.remark         = ((int)Score_source_remark.系统赠送).ToString();
                                user.total_score  += usr.score;
                                user.usable_score += user.total_score;
                                user.user_score_record.Add(usr);
                            }
                            tempUser.user = user;
                        }
                        tempUser.unionid          = wxUser.unionid;
                        tempUser.gzh_openid       = wxUser.openid;
                        tempUser.nickname         = wxUser.nickname;
                        tempUser.wx_head_protrait = wxUser.headimgurl;
                        tempUser.sex              = wxUser.sex;
                        tempUser.city             = wxUser.city;
                        tempUser.province         = wxUser.province;
                        tempUser.country          = wxUser.country;
                        tempUser.unsubscribe_time = DateTime.Now;
                        Wx_userService.EditEntity(tempUser);
                    }
                }
                else
                {
                    //新用户
                    var user = new user();
                    user.pid   = pid;
                    user.name  = wxUser.nickname;
                    user.sex   = wxUser.sex;
                    user.state = (int)User_state.正常;
                    user.isbuy = (int)Isbuy.未购买;
                    //首次关注赠送积分
                    var config_ruleItem = Config_ruleService.LoadEntities(n => n.name == "首次关注" && n.state == (int)State.可用).FirstOrDefault();
                    if (config_ruleItem != null)
                    {
                        var usr = new user_score_record();
                        usr.id    = Guid.NewGuid();
                        usr.score = config_ruleItem.value != null?Convert.ToDecimal(config_ruleItem.value) : 0;

                        usr.type           = (int)Score_type.收益;
                        usr.state          = (int)User_score_record_state.已完成;
                        usr.source_name    = "首次关注系统赠送";
                        usr.add_time       = DateTime.Now;
                        usr.remark         = ((int)Score_source_remark.系统赠送).ToString();
                        user.total_score  += usr.score;
                        user.usable_score += user.total_score;
                        user.user_score_record.Add(usr);
                    }
                    var newUser = new wx_user()
                    {
                        city             = wxUser.city,
                        country          = wxUser.country,
                        wx_head_protrait = wxUser.headimgurl,
                        nickname         = wxUser.nickname,
                        gzh_openid       = wxUser.openid,
                        province         = wxUser.province,
                        sex      = wxUser.sex,
                        add_time = DateTime.Now,
                        unionid  = wxUser.unionid,
                        state    = (int)WXUserState.未关注,//未关注
                        user     = user,
                    };
                    Wx_userService.AddEntity(newUser);
                    //SaveSyslog($"{wxUser.nickname}=>({Url})加入系统,pid={pid}", SysLogType.前台日志, "授权系统");
                }
                var url = $"{goUrl}?state={Guid.NewGuid().ToString().Substring(0, 4)}#token={token}";
                return(Redirect(url));
            }
            catch (ErrorJsonResultException ex)
            {
                return(Content(ex.Message));
            }
        }