using Alipay.AopSdk.Core;
using Alipay.AopSdk.Core.Domain;
using Alipay.AopSdk.Core.Request;
using Alipay.AopSdk.Core.Util;
using HHncore.Pass.Vpn.Request.Product;
using Hncore.Infrastructure.AliYun;
using Hncore.Infrastructure.Common;
using Hncore.Infrastructure.EntitiesExtension;
using Hncore.Infrastructure.Extension;
using Hncore.Infrastructure.Serializer;
using Hncore.Infrastructure.SMS;
using Hncore.Infrastructure.WebApi;
using Hncore.Pass.BaseInfo.Models;
using Hncore.Pass.BaseInfo.Request;
using Hncore.Pass.BaseInfo.Request.User;
using Hncore.Pass.PaymentCenter.Model;
using Hncore.Pass.PaymentCenter.Pay.WxPay;
using Hncore.Pass.PaymentCenter.WxPay.WechatJsPay;
using Hncore.Pass.Sells.Domain;
using Hncore.Pass.Sells.Service;
using Hncore.Pass.Vpn.Domain;
using Hncore.Pass.Vpn.Service;
using Hncore.Wx.Open;
using Home.Models;
using Host.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using UserService = Hncore.Pass.BaseInfo.Service.UserService;
using WxAppUserService = Hncore.Pass.BaseInfo.Service.WxAppUserService;
namespace Home.Controllers
{
    [Controller]
    [Route("[Controller]/[Action]")]
    public class UserController:Controller
    {
        UserService m_UserService;
        ProductAccountService m_ProductAccountService;
        AliDayu m_AliDayu;
        ArticleService m_ArticleService;
        ProductOrderService m_OrderService;
        Hncore.Pass.BaseInfo.Service.UserScoreService m_UserScoreService;
        private AgentService m_AgentService;
        ProductPackageService m_PackageService;
        ProductService m_ProductService;
        CouponService m_CouponService;
        Hncore.Pass.BaseInfo.Service.UserScoreService m_ScoreService;
        SellerTaoBaoService m_TaoBaoService;
        TaoBaoRefundService m_TaoBaoRefundService;
        WxAppUserService m_WxAppUserService;
        IConfiguration m_Configuration;
        UserChargeOrderService m_ChargeService;
        WxPayClient m_WxPayClient;
        private AgentService m_agentService;
        CouponUserOrginService m_CouponUserOrginService;
        public UserController(UserService _UserService
            , AliDayu _AliDayu
            , ProductAccountService _ProductAccountService
            , ArticleService _ArticleService
            , ProductOrderService _OrderService
            , Hncore.Pass.BaseInfo.Service.UserScoreService _UserScoreService
            , AgentService _AgentService
            , ProductPackageService _PackageService
            ,ProductService _ProductService
            , CouponService _CouponService
            , SellerTaoBaoService _TaoBaoService
            , TaoBaoRefundService _TaoBaoRefundService
            , Hncore.Pass.BaseInfo.Service.UserScoreService _ScoreService
            , WxAppUserService _WxAppUserService
            , UserChargeOrderService _ChargeService
            , IConfiguration _Configuration
            ,WxPayClient _WxPayClient
            , AgentService _agentService
            , CouponUserOrginService _CouponUserOrginService)
        {
            m_UserService = _UserService;
            m_AliDayu = _AliDayu;
            m_ProductAccountService = _ProductAccountService;
            m_ArticleService = _ArticleService;
            m_OrderService = _OrderService;
            m_UserScoreService = _UserScoreService;
            m_AgentService = _AgentService;
            m_PackageService = _PackageService;
            m_CouponService = _CouponService;
            m_TaoBaoService = _TaoBaoService;
            m_TaoBaoRefundService = _TaoBaoRefundService;
            m_ScoreService = _ScoreService;
            m_ProductService = _ProductService;
            m_WxAppUserService = _WxAppUserService;
            m_Configuration = _Configuration;
            m_ChargeService = _ChargeService;
            m_WxPayClient = _WxPayClient;
            m_agentService = _agentService;
            m_CouponUserOrginService = _CouponUserOrginService;
        }
        [UserAuth]
        public async Task<IActionResult> Index()
        {
            var userId = this.Request.GetUserInfo().UserId;
            var model = new UserHomeModel();
            model.UserModel = await m_UserService.GetById(userId);

            var accountQuery = m_ProductAccountService.Query(m => m.UserId == userId && m.DeleteTag==0);
            model.AccountModel.TotalCount = await accountQuery.CountAsync();
            model.AccountModel.ExpriedCount = await accountQuery.Where(m => m.EndTime < DateTime.Now).CountAsync();

            var orderQuery= m_OrderService.Query(m => m.UserId == userId);

            var todayOrderQuery = orderQuery.Where(m => (m.CreateTime - DateTime.Now).Days == 0);
            model.Statistic.TodayExpend = todayOrderQuery.Where(m => (m.OrderState == OrderStatus.PayOk || m.OrderState == OrderStatus.Complete)).Sum(m => m.PaymentAmount);
            model.Statistic.TodayRefund = todayOrderQuery.Where(m =>(m.OrderState == OrderStatus.AutoRefundOver || m.OrderState == OrderStatus.UserRefundOver)).Sum(m => m.RefundAmount);


            var monthOrderQuery = orderQuery.Where(m =>m.CreateTime.Month== DateTime.Now.Month);
            model.Statistic.MonthExpend = monthOrderQuery.Where(m => (m.OrderState == OrderStatus.PayOk || m.OrderState == OrderStatus.Complete)).Sum(m => m.PaymentAmount);
            model.Statistic.MonthRefund = monthOrderQuery.Where(m =>(m.OrderState == OrderStatus.AutoRefundOver || m.OrderState == OrderStatus.UserRefundOver)).Sum(m => m.RefundAmount);

            var yearOrderQuery = orderQuery.Where(m => (m.CreateTime - DateTime.Now).Days == 0);
            model.Statistic.YearExpend= yearOrderQuery.Where(m => (m.OrderState == OrderStatus.PayOk || m.OrderState == OrderStatus.Complete)).Sum(m => m.PaymentAmount);


            var chargeQuery = m_UserScoreService.Query(m => m.UserId == userId);
            model.Statistic.TodayCharege = chargeQuery.Where(m =>(m.ScoreType == ScoreType.ManagerAdd || m.ScoreType == ScoreType.TaoBaoAdd) && (m.CreateTime - DateTime.Now).Days == 0).Sum(m => m.ScoreValue);
            model.Statistic.MonthCharege = chargeQuery.Where(m => (m.ScoreType == ScoreType.ManagerAdd || m.ScoreType == ScoreType.TaoBaoAdd) && m.CreateTime.Month==DateTime.Now.Year).Sum(m => m.ScoreValue);


            model.TopNewsModel = await m_ArticleService.GetTop(6, Hncore.Pass.Vpn.Domain.ArticleCatalog.Top);

            return View(model);
        }

        [UserAuth]
        public async Task<IActionResult> IndexInfo()
        {
            var userId = this.Request.GetUserInfo().UserId;
            var model = new UserHomeModel();
            model.UserModel = await m_UserService.GetById(userId);

            var accountQuery = m_ProductAccountService.Query(m => m.UserId == userId);
            model.AccountModel.TotalCount = await accountQuery.CountAsync();
            model.AccountModel.ExpriedCount = await accountQuery.Where(m => m.EndTime < DateTime.Now).CountAsync();

            var orderQuery = m_OrderService.Query(m => m.UserId == userId);

            var todayOrderQuery = orderQuery.Where(m => (m.CreateTime - DateTime.Now).Days == 0);
            model.Statistic.TodayExpend = todayOrderQuery.Where(m => (m.OrderState == OrderStatus.PayOk || m.OrderState == OrderStatus.Complete)).Sum(m => m.PaymentAmount);
            model.Statistic.TodayRefund = todayOrderQuery.Where(m => (m.OrderState == OrderStatus.AutoRefundOver || m.OrderState == OrderStatus.UserRefundOver)).Sum(m => m.RefundAmount);


            var monthOrderQuery = orderQuery.Where(m => m.CreateTime.Month == DateTime.Now.Month);
            model.Statistic.MonthExpend = monthOrderQuery.Where(m => (m.OrderState == OrderStatus.PayOk || m.OrderState == OrderStatus.Complete)).Sum(m => m.PaymentAmount);
            model.Statistic.MonthRefund = monthOrderQuery.Where(m => (m.OrderState == OrderStatus.AutoRefundOver || m.OrderState == OrderStatus.UserRefundOver)).Sum(m => m.RefundAmount);

            var yearOrderQuery = orderQuery.Where(m => (m.CreateTime - DateTime.Now).Days == 0);
            model.Statistic.YearExpend = yearOrderQuery.Where(m => (m.OrderState == OrderStatus.PayOk || m.OrderState == OrderStatus.Complete)).Sum(m => m.PaymentAmount);


            var chargeQuery = m_UserScoreService.Query(m => m.UserId == userId);
            model.Statistic.TodayCharege = chargeQuery.Where(m => (m.ScoreType == ScoreType.ManagerAdd || m.ScoreType == ScoreType.TaoBaoAdd) && (m.CreateTime - DateTime.Now).Days == 0).Sum(m => m.ScoreValue);
            model.Statistic.MonthCharege = chargeQuery.Where(m => (m.ScoreType == ScoreType.ManagerAdd || m.ScoreType == ScoreType.TaoBaoAdd) && m.CreateTime.Month == DateTime.Now.Year).Sum(m => m.ScoreValue);


            model.TopNewsModel = await m_ArticleService.GetTop(6, Hncore.Pass.Vpn.Domain.ArticleCatalog.Top);

            return View(model);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public async Task<ApiResult> Login([FromBody] LoginRequest request)
        {
            var user = await m_UserService.Login(request);

            var appId = m_Configuration["WxApps:AppId"];
            var wxUser = await m_WxAppUserService.GetWxUser(appId, user.User.Id);
            if (wxUser != null)
                user.User.OpenId = wxUser.Openid;
            this.HttpContext.Response.Cookies.Append("token", user.Token);
            this.HttpContext.Response.Cookies.Append("userInfo", user.User.ToJson());
            return new ApiResult(user);
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public async Task<IActionResult> LoginOut()
        {
            this.HttpContext.Response.Cookies.Delete("token");
            this.HttpContext.Response.Cookies.Delete("userInfo");
            return Redirect("/");
        }

        /// <summary>
        /// 手机验证码登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public async Task<ApiResult> PhoneLogin([FromBody] PhoneModel request)
        {
            var key = $"User_Login:{request.Phone}";
            var code = await RedisHelper.GetAsync(key);
            if (request.Code != code)
            {
                return new ApiResult(ResultCode.C_Access_Forbidden, "验证码不正确或者过期");
            }
            var userEntity = m_UserService.Query(m => m.Phone == request.Phone || m.LoginCode == request.Phone).FirstOrDefault();
            if (userEntity == null)
            {
                return new ApiResult(ResultCode.C_Access_Forbidden, "用户不存在");
            }
            var user = await m_UserService.Login(new LoginRequest()
            {
                Logincode = userEntity.LoginCode,
                Password = userEntity.Password
            });
            this.HttpContext.Response.Cookies.Append("token", user.Token);
            this.HttpContext.Response.Cookies.Append("userInfo", user.User.ToJson());
            return new ApiResult(user);
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public IActionResult Regist()
        {
            return View();
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public async Task<ApiResult> Regist([FromBody] PhoneModel request)
        {
            var key = $"User_Code:{request.Phone}";

            if (request.Phone.NotHas())
            {
                return new ApiResult(ResultCode.C_Access_Forbidden, "手机号不能为空");
            }

            var code = await RedisHelper.GetAsync(key);
            if (request.Code != code)
            {
                return new ApiResult(ResultCode.C_Access_Forbidden, "验证码不正确或者过期");
            }
            var userEntity = new User()
            {
                CreateType = UserCreateType.UserRegist,
                LoginCode = request.Phone,
                Password = request.Pwd,
                Phone = request.Phone,
                Wx=request.Wx,
                QQ=request.QQ,
                id_code=""
            };

            var ret = await m_UserService.Regist(userEntity);
            if (ret.Code != ResultCode.C_SUCCESS) return ret;
            var userLogin = await m_UserService.Login(new LoginRequest()
            {
                Logincode = request.Phone,
                Password = request.Pwd
            });
            this.HttpContext.Response.Cookies.Append("token", userLogin.Token);
            this.HttpContext.Response.Cookies.Append("userInfo", userLogin.User.ToJson());
            return new ApiResult(userLogin);
        }

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public IActionResult FindPwd()
        {
            return View();
        }


        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public async Task<ApiResult> FindPwd([FromBody] PhoneModel request)
        {
            var key = $"FindUser_Code:{request.Phone}";

            if (request.Phone.NotHas())
            {
                return new ApiResult(ResultCode.C_Access_Forbidden, "手机号不能为空");
            }

            var code = await RedisHelper.GetAsync(key);
            if (request.Code != code)
            {
                return new ApiResult(ResultCode.C_Access_Forbidden, "验证码不正确或者过期");
            }
            var user = await m_UserService.GetByPhone(request.Phone);
            if (user==null)  return new ApiResult(ResultCode.C_Access_Forbidden, "手机号不存在");
            return await m_UserService.UpdatePwd(user, request.Pwd);

        }


        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        // [HttpGet, AllowAnonymous]
        // public async Task<ApiResult> SendPhoneCode(string phone,string key)
        // {
        //         return new ApiResult(ResultCode.C_SUCCESS, "验证码已发送到您的手机");
        // }

        

        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public async Task<ApiResult> SendPhoneCodevefy(string phone,string key)
        {
             key = $"{key}:{phone}";
          
            if (key.StartsWith("User_Code:") &&m_UserService.Exist(m => m.LoginCode == phone || m.Phone == phone))
            {
                return new ApiResult(ResultCode.C_ALREADY_EXISTS_ERROR, "该手机号已经被注册了");
            }


            var code = await RedisHelper.GetAsync(key);
            if (code.Has())
            {
                return new ApiResult(ResultCode.C_Access_Forbidden, "请稍后再试");
            }
            code = ValidateCodeHelper.MakeNumCode(4);
            await RedisHelper.SetAsync(key, code, 60);
            var ret = AliSmsService.Send( "SMS_186355045", new { code }, "聚IP商城", phone);
            if (ret)
            {
                return new ApiResult(ResultCode.C_SUCCESS, "验证码已发送到您的手机");
            }
            return new ApiResult(ResultCode.C_UNKNOWN_ERROR, "验证码已发失败");
        }

        [HttpPost, UserAuth]
        public async Task<ApiResult> OrginAccountAuth([FromBody]OriginAccountAuthRequest request)
        {
            var user = this.Request.GetUserInfo();

            List<string> accounts = new List<string>();

            if (request.StartNum > 0 && request.Count > 0)
            {
                var end = request.StartNum + request.Count;
                for (var i = request.StartNum; i < end; i++)
                {
                    var account = $"{ request.Account}{i}";
                   // if (!m_ProductAccountService.Exist(m =>  m.Account == account))//m.ProductId == request.ProductId &&
                   accounts.Add(account);
                }
            }
            else
            {
                //if (m_ProductAccountService.Exist(m =>  m.Account == request.Account))//m.ProductId == request.ProductId &&
                //    return new ApiResult(ResultCode.C_ALREADY_EXISTS_ERROR, "该账号已经存在了");

                accounts.Add(request.Account);
            }

            List<string> error = new List<string>();
            foreach (var accountItem in accounts)
            {
                if (m_ProductAccountService.Exist(m =>m.ProductId== request.ProductId&& m.Account == accountItem))
                {
                    error.Add($"[{accountItem}]已存在");
                    continue;
                }
                 var originModel = await m_AgentService.GetOriginAccountInfo(request.ProductId, accountItem, request.Pwd);
                if (originModel.Code != ResultCode.C_SUCCESS)
                {

                    error.Add($"[{accountItem}]{originModel.Message}");
                    continue;
                }
                var package = await m_PackageService.Query(m => m.ProductId == request.ProductId && m.OriginName == originModel.Data.Package).FirstOrDefaultAsync();
                var product = await m_ProductService.GetById(request.ProductId);
                await m_ProductAccountService.Add(new ProductAccountEntity()
                {
                    Account = accountItem,
                    AccountType = (int)Hncore.Pass.Vpn.Domain.AccountType.Origin,
                    PackageId = package == null ? 0 : package.Id,
                    ChargeStatus = AccountChargeStatus.Normal,
                    ConnectCount = Convert.ToInt32(originModel.Data.ConnectCount),
                    EndTime = originModel.Data.RealEndTime,
                    PackageName = package == null ? originModel.Data.Package : package.Name,
                    ProductId = product.Id,
                    ProductName = product.Name,
                    Pwd = originModel.Data.Pwd,
                    StartTime = DateTime.Parse(originModel.Data.RegistTime),
                    Remark = "原系统认证",
                    UserId = user.UserId,
                    UserCode = user.LoginName,
                });
            }
            if (error.Count > 0)
            {
                return new ApiResult(ResultCode.C_IGNORE_ERROR, string.Join("\n", error));
            }
            return new ApiResult(1);
        }

        [HttpGet]
        [UserAuth]
        public async Task<IActionResult> MyOrders([FromQuery]OrderSearchModel request)
        {
            var userId =  this.Request.GetUserInfo().UserId;

            var orderQuery = m_OrderService.Query(m => m.UserId == userId && m.DeleteTag == 0);
            orderQuery = orderQuery.Where(m => m.OrderState == OrderStatus.PayOk || m.OrderState == OrderStatus.Complete);
            if (request.OrderType > 0)
            {
                orderQuery = orderQuery.Where(m => (int)m.OrderType == request.OrderType);
            }
            if (request.ProductId > 0)
            {
                orderQuery = orderQuery.Where(m => m.ProductId == request.ProductId);
            }

            if (request.PackageId !="0")
            {
                orderQuery = orderQuery.Where(m => m.PackageName == request.PackageId);
            }

            if (request.ETime.HasValue && request.BTime.HasValue)
            {
                orderQuery = orderQuery.Where(m => m.CreateTime >= request.BTime && m.CreateTime <= request.ETime);
            }

            if (request.KeyWord.Has())
            {
                orderQuery = orderQuery.Where(m =>m.OrderNo.Contains(request.KeyWord)||m.Accounts.Contains(request.KeyWord));
            }
            var data =await orderQuery.OrderByDescending(m => m.Id).ListPagerAsync(request.PageSize, request.PageIndex, true);         
            return View(data);
        }

        [HttpGet]
        [UserAuth]
        public async Task<IActionResult> MyRefundOrders([FromQuery]OrderSearchModel request)
        {
            var userId = this.Request.GetUserInfo().UserId;

            var orderQuery = m_OrderService.Query(m => m.UserId == userId);
            orderQuery = orderQuery.Where(m => m.OrderState == OrderStatus.AutoRefundOver || m.OrderState == OrderStatus.UserRefundOver || m.OrderState == OrderStatus.RequestRefund);            
            if (request.OrderType > 0)
            {
                orderQuery = orderQuery.Where(m => (int)m.OrderType == request.OrderType);
            }
            if (request.ProductId > 0)
            {
                orderQuery = orderQuery.Where(m => m.ProductId == request.ProductId);
            }

            if (request.PackageId != "0")
            {
                orderQuery = orderQuery.Where(m => m.PackageName == request.PackageId);
            }

            if (request.ETime.HasValue && request.BTime.HasValue)
            {
                orderQuery = orderQuery.Where(m => m.CreateTime >= request.BTime && m.CreateTime <= request.ETime);
            }

            if (request.KeyWord.Has())
            {
                orderQuery = orderQuery.Where(m => m.OrderNo.Contains(request.KeyWord) || m.Accounts.Contains(request.KeyWord));
            }
            var data = await orderQuery.OrderByDescending(m => m.Id).ListPagerAsync(request.PageSize, request.PageIndex, true);
            return View(data);
        }


        [HttpGet]
        [UserAuth]
        public async Task<IActionResult> MyAccounts([FromQuery]AccountSearchModel request=null )
        {
            request = request ?? new AccountSearchModel();
            var userId = this.Request.GetUserInfo().UserId;

            Expression<Func<ProductAccountEntity, bool>> exp = m => m.UserId == userId;
            exp = exp.And(m => m.DeleteTag == 0);
            if (request.ProductId > 0)
            {
                exp = exp.And(m => m.ProductId == request.ProductId);
            }

            if (request.PackageId != "0")
            {
                exp = exp.And(m => m.PackageName == request.PackageId);
            }

            if (request.ExpiredDay > -100)
            {
                if (request.ExpiredDay > 0){
                    exp = exp.And(m => Math.Ceiling((m.EndTime - DateTime.Now).Value.TotalDays) <= request.ExpiredDay && m.EndTime > DateTime.Now);
                } else if (request.ExpiredDay < 0 && request.ExpiredDay>-4) {
                    exp = exp.And(m => Math.Ceiling((DateTime.Now - m.EndTime).Value.TotalDays) <= Math.Abs(request.ExpiredDay) && m.EndTime < DateTime.Now);
                } else if (request.ExpiredDay==-4) {
                    exp = exp.And(m => Math.Ceiling((m.EndTime - DateTime.Now).Value.TotalDays) <= -4);
                } else if (request.ExpiredDay==-5) {
                    exp = exp.And(m => m.EndTime > DateTime.Now);
                } else if (request.ExpiredDay==-6) {
                    exp = exp.And(m => m.EndTime < DateTime.Now);
                }
                exp = exp.And(m => m.PackageName != "测试卡");
            }

            if (request.ETime.HasValue && request.BTime.HasValue)
            {
                exp = exp.And(m => m.EndTime >= request.BTime && m.EndTime <= request.ETime);
            }

            if (request.KeyWord.Has())
            {
                exp = exp.And(m => m.Account.Contains(request.KeyWord));
            }

            //var ret = await m_ProductAccountService.PageDesc(request.PageIndex,request.PageSize, exp,true,m=>m.Id);
            var ret = await m_ProductAccountService.Query(exp, true).OrderByDescending(m=>m.Id).QueryPager(1000,1).ToListAsync();
            return View(ret);
        }
        [HttpGet]
        [UserAuth]
        public async Task<IActionResult> AssignAddress([FromQuery]AccountSearchModel request=null )
        {
        
            return View();
        }

        [HttpGet]
        [UserAuth]
        public async Task<IActionResult> MyCoupons()
        {
            var userId =this.Request.GetUserInfo().UserId;   
            var model = await m_CouponService.GetUserCoupon(userId);     
            return View(model);
        }

        [HttpGet]
        [UserAuth]
        public IActionResult CashOut()
        {
            var userId =this.Request.GetUserInfo().UserId;           
            return View();
        }

        
        [HttpGet]
        [UserAuth]
        public IActionResult RosOrder()
        {
            var userId =this.Request.GetUserInfo().UserId;           
            return View();
        }

        [HttpGet]
        [UserAuth]
        public IActionResult MyMoney()
        {
            var userId =this.Request.GetUserInfo().UserId;           
            return View();
        }

        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public IActionResult WebLogin(string redirect="")
        {
            ViewBag.redirect = redirect;
            return View("Login");
        }

        /// <summary>
        /// 淘宝订单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public async Task<IActionResult> TaoBao()
        {
            Func<string, Task<string>> process = async (data) =>
            {
                var notifyOrder = data.FromJsonTo<TaoBaoNotifyModel>();
                LogHelper.Info("TaoBao process");
                if(notifyOrder.Payment == "10.00" && (notifyOrder.SellerNick == "聚ip商城动态ip代理" || notifyOrder.SellerNick == "老鹰动态pptp")||notifyOrder.SellerNick == "强子pptp动态"){
                    return "您好，"+notifyOrder.Payment+"元已充值到充值到您的会员中";
                }
                if (notifyOrder == null || notifyOrder.Tid.NotHas())
                    return "";

                if (m_ScoreService.ExistTaoBaoScore(notifyOrder.Tid))
                    return "";
                // var phone = notifyOrder.ReceiverMobile.NotHas() ? notifyOrder.ReceiverPhone : notifyOrder.ReceiverMobile;
                // if (phone.NotHas()) return false;
                var userEntity = await m_UserService.Query(m => m.TaoBao == notifyOrder.BuyerNick).FirstOrDefaultAsync();
                var phone = notifyOrder.BuyerNick;

                string pas_result = "";
                Random rd = new Random(Guid.NewGuid().GetHashCode());
                for (int i = 0; i < 6; i++)
                {
                    int rnd = rd.Next(0, 9);
                    pas_result += rnd.ToString();
                }

                // Console.WriteLine("==================================================================");
                
                string msg = "";

                if (userEntity == null)
                {
                    userEntity = new User()
                    {
                        CreateType = UserCreateType.TaoBaoRegist,
                        LoginCode = phone,
                        Password = pas_result,
                        Phone = phone,
                        TaoBao= notifyOrder.BuyerNick,
                        id_code=""
                    };
                    var ret = await m_UserService.Regist(userEntity);
                     msg = "您好，打开网址：juip.com，登录会员名："+phone+"（"+notifyOrder.Payment+"元已充值到此账户），密码："+pas_result+"。这个会员名和密码不能直接使用，是用来登录官网的。登录后点击网站上方的-产品购买，即可完成开通或续费。在官网购买的账号密码可以直接使用。恭喜您本次获得优惠券（满4元减1元，满20元减3元，满54元减5元，满130元减15元，满490元减30元），各一张。欢迎您多来淘宝下单(人工客服在线时间：上午八点到晚上十一点半)";
                    if (ret.Code != ResultCode.C_SUCCESS) return msg;
                   
                } else {
                    phone = userEntity.Phone;
                    
                    if(userEntity.TaoBao == null){
                        userEntity.TaoBao= notifyOrder.BuyerNick;
                        await m_UserService.Update(userEntity);
                    }
                    msg = "您好，"+notifyOrder.Payment+"元已充值到充值到您的会员中,会员号为："+userEntity.LoginCode+"，打开网址：juip.com，登录后点击网站上方的-产品购买，即可完成开通或续费。恭喜您本次获得优惠券（满4元减1元，满20元减3元，满54元减5元，满130元减15元，满490元减30元），各一张。欢迎您多来淘宝下单(人工客服在线时间：上午八点到晚上十一点半)";
                
                }

                var amountInfo = new UpdateAmountRequest()
                {
                    OperateUserName= phone,
                    Amount = decimal.Parse(notifyOrder.Payment),
                    OpAmountType = ScoreType.TaoBaoAdd,
                    UserId = userEntity.Id,
                    AttchInfo = notifyOrder.Tid
                };
                var retAmount = await m_UserService.UpdateAmount(amountInfo);
                await m_CouponService.TaoBaoGive(userEntity.Id, 11, notifyOrder.BuyerNick);
                await m_CouponService.TaoBaoGive(userEntity.Id, 12, notifyOrder.BuyerNick);
                await m_CouponService.TaoBaoGive(userEntity.Id, 13, notifyOrder.BuyerNick);
                await m_CouponService.TaoBaoGive(userEntity.Id, 14, notifyOrder.BuyerNick);
                await m_CouponService.TaoBaoGive(userEntity.Id, 15, notifyOrder.BuyerNick);


                var taobaoEntity = notifyOrder.MapTo<TaoBaoOrderEntity>();
                taobaoEntity.Phone = phone;
                taobaoEntity.SkuPropertiesName = notifyOrder.Orders.FirstOrDefault()?.SkuPropertiesName;

                await m_TaoBaoService.Add(taobaoEntity);

                
                // await Task.Delay(3000);
                // Console.WriteLine("===================================================================");
                // var send_msg_info = await m_TaoBaoService.SengMsg(notifyOrder.Tid,msg);
                // Console.WriteLine("===================================================================");
                // Console.WriteLine(send_msg_info);
                // Console.WriteLine("===================================================================");

                return msg;
            };
            Func<string, Task<bool>> refunds = async (data) =>
            {
                var refundInfo = data.FromJsonTo<TaoBaoRefundModel>();

                LogHelper.Info("TaoBao process");
                if (refundInfo == null || refundInfo.RefundId.NotHas())
                    return false;

                var his_order= m_TaoBaoService.Query(m => m.Tid == refundInfo.Tid).FirstOrDefault();
                refundInfo.Phone = his_order.Phone;

                var taobaoEntity = refundInfo.MapTo<TaoBaoRefundEntity>();
                
                await m_TaoBaoRefundService.Add(taobaoEntity);

                return true;
            };
            long aopic = long.Parse(this.Request.Query["aopic"]);
            string datainfo = this.Request.Form["json"];
            var refundInfos = datainfo.FromJsonTo<TaoBaoRefundModel>();
            var info = "";
            if (aopic == 2){
                info = await m_TaoBaoService.ReceivedMsg(this.Request, process);
            } else if(aopic == 256){//退款
                var his_order= m_TaoBaoRefundService.Query(m => m.Tid == refundInfos.Tid).FirstOrDefault();
                if (his_order == null){
                    info = await m_TaoBaoRefundService.ReceivedRefundMsg(this.Request, refunds);
                } else {
                    his_order.status = 0;
                    his_order.RefundFee = refundInfos.RefundFee;
                    his_order.Modified = refundInfos.Modified;
                    await m_TaoBaoRefundService.Update(his_order);
                }
                
            }else if(aopic == 65536){//卖家同意退款
                
                var his_order= m_TaoBaoRefundService.Query(m => m.Tid == refundInfos.Tid).FirstOrDefault();
                his_order.status = 1;
                
                await m_TaoBaoRefundService.Update(his_order);
                
            }else if(aopic == 262144){//拒绝退款
                var his_order= m_TaoBaoRefundService.Query(m => m.Tid == refundInfos.Tid).FirstOrDefault();
                his_order.status = 2;

                
                await m_TaoBaoRefundService.Update(his_order);
                
            }else if(aopic == 32768){//关闭
                var his_order= m_TaoBaoRefundService.Query(m => m.Tid == refundInfos.Tid).FirstOrDefault();
                his_order.status = 3;

                
                await m_TaoBaoRefundService.Update(his_order);
                
            }
            return Content(info);
        }

        [HttpPost, UserAuth]
        public async Task<IActionResult> UpdateInfo(User request)
        {
            var userEntity = await this.m_UserService.GetById(this.Request.GetUserInfo().UserId);
            userEntity.Wx = request.Wx;
            userEntity.QQ = request.QQ;
            userEntity.TaoBao = request.TaoBao;
            userEntity.Email = request.Email;
            userEntity.WangWang = request.WangWang;
            var ret = await m_UserService.Update(userEntity);
            var flag = m_CouponUserOrginService.Exist(m => m.ToUser == userEntity.Id && m.OriginType == Enums.CouponOriginType.UserInfo);
            if (!flag)
                await m_CouponService.Give(6, "", userEntity.Id, 1, Hncore.Pass.Sells.Domain.Enums.CouponOriginType.UserInfo, "完善信息");
            return RedirectToAction("Index");
        }

        [HttpPost, UserAuth]
        public async Task<ApiResult> UpdatePwd([FromBody]UpdatePwdModel request)
        {
            if (request.NewPwd != request.ConfirmPwd)
            {
                return new ApiResult(ResultCode.C_INVALID_ERROR,"密码不一致");
            }
            var ret = await this.m_UserService.UpdatePwd(this.Request.GetUserInfo().UserId, request.OldPwd, request.NewPwd);
            return ret;
        }
        [HttpPost, UserAuth]
        public async Task<ApiResult> UpdateAccountPwd([FromBody]UpdateAccountPwdRequest request)
        {
            return await m_ProductAccountService.UpdateAccountPwd(request);           
        }

        [HttpPost, AllowAnonymous]
        public async Task<ApiResult> ApiUpdateAccountPwd([FromBody]UpdateAccountPwdRequest request)
        {
            //通过apikey获取用户信息
            var userEntity = m_UserService.Query(m => m.apikey == request.apikey).FirstOrDefault();
            if (userEntity == null)
            {
                return new ApiResult(ResultCode.C_INVALID_ERROR, "apikey不正确");
            }
            return await m_ProductAccountService.ApiUpdateAccountPwd(request,userEntity.Id);           
        }




        [HttpGet, AllowAnonymous]
        public IActionResult MP_GetUserInfo(string appid, string callbakUrl, string state = "")
        {
            callbakUrl = callbakUrl.UrlEncode();
            var baseUrl = m_Configuration["BaseInfoUrl"];
            var getUserInfo_Callback = $"{baseUrl}User/MP_GetUserInfo_Callback?returnUrl={callbakUrl}&appid={appid}";

            getUserInfo_Callback = getUserInfo_Callback.UrlEncode();

            var wxUrl = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={getUserInfo_Callback}&response_type=code&scope=snsapi_userinfo&state={state}#wechat_redirect";
            LogHelper.Debug("WxAuth_GetUserInfo", $"wxUrl={wxUrl}");

            return Redirect(wxUrl);
        }

        /// <summary>
        /// 公众平台 网页授权 回调
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpGet, AllowAnonymous]
        public async Task MP_GetUserInfo_Callback(string appid, string code, string state, string returnUrl)
        {
            LogHelper.Debug("GetUserInfo_Callback", $"appid={appid},code={code}, state={state}, returnUrl={returnUrl}");

            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                return;
            }

            var access_token = "";
            var openid = "";

            var weToken = await WxOpenApi.GetWebAccessToken(appid, code);
            if (weToken != null && weToken.errcode == 0)
            {
                access_token = weToken.access_token;
                openid = weToken.openid;
            }
            else
            {
                LogHelper.Error("GetWebAccessToken", weToken?.errmsg);
                return;
            }

            var userInfo = await WxOpenApi.GetUserinfoByWebAccessToken(access_token, openid);

            if (userInfo==null)
            {
                LogHelper.Error("GetUserinfoByWebAccessToken",$"access_token={access_token},openid={openid}");
                return;
            }
            if (userInfo.errcode > 0)
            {
                LogHelper.Error("GetUserinfoByWebAccessToken", userInfo.errmsg);
                return;
            }
            if (state.Has())
            {
                var userId = Convert.ToInt32(state);
                var wx = new Hncore.Pass.BaseInfo.Models.WxAppUserEntity()
                {
                    Appid = appid,
                    UserId = userId,
                    HeadImgUrl = userInfo.headimgurl,
                    NickName = userInfo.nickname,
                    City = userInfo.city,
                    Country = userInfo.country,
                    Openid = userInfo.openid,
                    UserName = userInfo.nickname
                };
                await m_WxAppUserService.Bind(wx);
            }
            var wxUserInfo = await m_WxAppUserService.GetWxUser(appid, userInfo.openid);
            if (wxUserInfo != null)
            {               
                var userEntity = await m_UserService.GetById(wxUserInfo.UserId);
                var loginRet = m_UserService.LoginInternal(userEntity, wxUserInfo);
                this.HttpContext.Response.Cookies.Append("token", loginRet.Token);
                this.HttpContext.Response.Cookies.Append("userInfo", loginRet.User.ToJson());
                this.Response.Redirect(returnUrl);
            }
            else
            {
                var baseUrl = m_Configuration["BaseInfoUrl"];
                var loginUrl = $"{baseUrl}User/WebLogin?redirect={returnUrl}";
                //   returnUrl = UrlHelper.SetUrlParam(returnUrl, "act", "login");
                this.Response.Redirect(loginUrl);
            }                  
        }


        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>

        [HttpPost, UserAuth]
        public async Task<ApiResult> CreateOrder([FromBody]CreateOrderRequest request)
        {
            var userId = this.Request.GetUserInfo().UserId;
            var ret = await m_ChargeService.CreateOrder(request, userId);

            if (ret.Code != ResultCode.C_SUCCESS)
            {
                return ret;
            }

            var data = new ChargeOrderPayModel()
            {
                OrderInfo = ret.Data,
            };
            if (ret.Data.PayChannel == UPayChannel.WxH5|| ret.Data.PayChannel == UPayChannel.WxPc||ret.Data.PayChannel == UPayChannel.WxMp)
            {
                var url = await CreateWxPayOrder(ret.Data);
                data.PayData = url;
                return new ApiResult(data);
            }
            else
            {
                var body = await CreateAliPayOrder(ret.Data);
                data.PayData = body;
            }
            return new ApiResult(data);
        }
        [HttpGet,AllowAnonymous]
        public async Task<ApiResult> IsPay(string orderNo)
        {
            var orderInfo = await m_ChargeService.GetOrderByNo(orderNo);
            if (orderInfo.OrderState == UOrderStatus.PayOk || orderInfo.OrderState == UOrderStatus.Complete)
                return new ApiResult(1);
            else
                return new ApiResult(0);
        }


        #region 微信支付
        private async Task<string> CreateWxPayOrder(UserChargeOrderEntity request)
        {
            string callBackUrl = m_Configuration["UNotifyUrl"];
            var wxAppId = m_Configuration["WxApps:AppID"];
            var wxMchId = m_Configuration["WxApps:MchId"];
            var wxMchKey = m_Configuration["WxApps:MchKey"];
            var mchInfo = new MchInfo()
            {
                MchId = wxMchId,
                Key = wxMchKey
            };

            string createOrderRes = "";
            if (request.PayChannel == UPayChannel.WxPc)
            {
                var payRequest = new WxScanPayCreateOrderRequest()
                {
                    AppId = wxAppId,
                    Body = request.OrderName,
                    MchId = wxMchId,
                    NotifyUrl = callBackUrl,
                    OutTradeNo = request.OrderNo,
                    StoreId = 2,
                    TenantId = 1157,
                    TotalFee = (int)(request.PaymentAmount * 100),
                    ProductId = request.OrderAmount.ToString(),
                    TimeExpire = DateTime.Now.AddMinutes(15).ToString("yyyyMMddHHmmss")
                };
                createOrderRes = await m_WxPayClient.ScanPayCreateOrderAsync(payRequest, mchInfo);
            }
            else if (request.PayChannel == UPayChannel.WxH5)
            {
                var payRequest = new WxH5PayCreateOrderRequest()
                {
                    AppId = wxAppId,
                    Body = request.OrderName,
                    MchId = wxMchId,
                    NotifyUrl = callBackUrl,
                    OutTradeNo = request.OrderNo,
                    StoreId = 2,
                    TenantId = 1157,
                    TotalFee = (int)(request.PaymentAmount * 100),
                    ProductId = request.OrderAmount.ToString(),
                    TimeExpire = DateTime.Now.AddMinutes(15).ToString("yyyyMMddHHmmss")
                };
                createOrderRes = await m_WxPayClient.H5PayCreateOrderAsync(payRequest, mchInfo);
            }
            else
            {
                var wxUserInfo = await m_WxAppUserService.GetWxUser(wxMchId, request.UserId);
                var payRequest = new WxJsPayCreateOrderRequest()
                {
                    AppId = wxAppId,
                    Body = request.OrderName,
                    MchId = wxMchId,
                    NotifyUrl = callBackUrl,
                    OutTradeNo = request.OrderNo,
                    StoreId = 2,
                    TenantId = 1157,
                    TotalFee = (int)(request.PaymentAmount * 100),
                    UserOpenId = wxUserInfo.Openid,
                    TimeExpire = DateTime.Now.AddMinutes(15).ToString("yyyyMMddHHmmss")
                };
                createOrderRes = await m_WxPayClient.JsPayCreateOrderAsync(payRequest, mchInfo);
            }
            return createOrderRes;
        }

        [HttpPost, AllowAnonymous]
        public async Task<string> WxOrderCallBack()
        {
            var wxAppId = m_Configuration["WxApps:AppID"];
            var wxMchId = m_Configuration["WxApps:MchId"];
            var wxMchKey = m_Configuration["WxApps:MchKey"];
            try
            {
                string xml = "";
                LogHelper.Trace("微信支付回调开始", "Notify");
                if (Request.Body.CanSeek)
                {
                    Request.Body.Position = 0;
                }

                using (System.IO.StreamReader reader = new System.IO.StreamReader(Request.Body))
                {
                    xml = reader.ReadToEnd();
                }

                LogHelper.Trace("微信支付回调，原始数据：", $"{xml}");

                WxPayChecker payData = new WxPayChecker();


                payData.FromXmlNoCheckSign(xml);

                if (!payData.IsSet("out_trade_no"))
                {
                    return FailXml();
                }

                // 给支付平台的订单号为支付记录id
                string orderId = payData["out_trade_no"];

                string TransactionId = payData["transaction_id"];

                var order = await m_ChargeService.GetOrderByNo(orderId);
                if (order.OrderState == UOrderStatus.Complete || order.OrderState == UOrderStatus.PayOk)
                    return SuccessXml();

                var queryRet = await m_WxPayClient.OrderQuery(new WxJsPayOrderQueryRequest()
                {
                    AppId = wxAppId,
                    NonceStr = payData.GenerateNonceStr(),
                    TransactionId = TransactionId
                }, new MchInfo() { MchId = wxMchId, Key = wxMchKey });
                if (!queryRet) return FailXml();


                payData.MchKey = wxMchKey;
                if (!payData.CheckSign()) return FailXml();
                order.OrderState = UOrderStatus.PayOk;
                order.TradeNo = TransactionId;
                order.UpdateTime = DateTime.Now;
                await m_ChargeService.Update(order);
                await m_ChargeService.ProcessOrderAccount(order);
            }
            catch (Exception e)
            {
                LogHelper.Error("微信支付通知处理失败", e);

                return FailXml();
            }
            return SuccessXml();
        }

        public string FailXml()
        {
            return "<xml><return_code>FAIL</return_code> </xml>";
        }

        private string SuccessXml()
        {
            return "<xml><return_code>SUCCESS</return_code> </xml>";
        }

        #endregion


        #region 阿里支付
        private async Task<string> CreateAliPayOrder(UserChargeOrderEntity request)
        {          
            if (request.PayChannel == UPayChannel.AliPc)
            {
               var  Ali_APP_ID = m_Configuration["Aliyun:Pay:AppId"];
               var  Ali_APP_PRIVATE_KEY = m_Configuration["Aliyun:Pay:PrivateKey"];
               var  ALIPAY_PUBLIC_KEY = m_Configuration["Aliyun:Pay:PublicKey"];//支付宝的公钥，而不是应用的公钥
                string callBackUrl = m_Configuration["Aliyun:Pay:UNotifyUrl"];
                string ReturnUrl = m_Configuration["Aliyun:Pay:UReturnUrl"];


                // 组装业务参数model
                AlipayTradePagePayModel model = new AlipayTradePagePayModel
                {
                    Body = request.OrderName,
                    Subject = request.OrderName,
                    TotalAmount = request.PaymentAmount.ToString(),
                    OutTradeNo = request.OrderNo,
                    ProductCode = "FAST_INSTANT_TRADE_PAY",//QUICK_WAP_PAY
                    TimeoutExpress = "15m"
                };

                AlipayTradePagePayRequest aliRequest = new AlipayTradePagePayRequest();
                // 设置同步回调地址
                aliRequest.SetReturnUrl(ReturnUrl);
                // 设置异步通知接收地址
                aliRequest.SetNotifyUrl(callBackUrl);
                // 将业务model载入到request
                aliRequest.SetBizModel(model);

                var _aopClient = new DefaultAopClient("https://openapi.alipay.com/gateway.do", Ali_APP_ID, Ali_APP_PRIVATE_KEY);

                var response = await _aopClient.PageExecuteAsync(aliRequest);

                return response.Body;

            }
            else if (request.PayChannel == UPayChannel.AliH5)
            {
              var  Ali_APP_ID = m_Configuration["Aliyun:PayH5:AppId"];
              var  Ali_APP_PRIVATE_KEY = m_Configuration["Aliyun:PayH5:PrivateKey"];
              var  ALIPAY_PUBLIC_KEY = m_Configuration["Aliyun:PayH5:PublicKey"];
              var  callBackUrl = m_Configuration["Aliyun:PayH5:UNotifyUrl"];
              var  ReturnUrl = m_Configuration["Aliyun:PayH5:UReturnUrl"];

                // 组装业务参数model
                AlipayTradeWapPayModel model = new AlipayTradeWapPayModel
                {
                    Body = request.OrderName,
                    Subject = request.OrderName,
                    TotalAmount = request.PaymentAmount.ToString(),
                    OutTradeNo = request.OrderNo,
                    ProductCode = "QUICK_WAP_PAY",
                    QuitUrl = this.Request.GetUrl(),
                    TimeoutExpress = "15m"
                };

                AlipayTradeWapPayRequest aliRequest = new AlipayTradeWapPayRequest();
                // 设置同步回调地址
                aliRequest.SetReturnUrl(ReturnUrl);
                // 设置异步通知接收地址
                aliRequest.SetNotifyUrl(callBackUrl);
                // 将业务model载入到request
                aliRequest.SetBizModel(model);

                var _aopClient = new DefaultAopClient("https://openapi.alipay.com/gateway.do", Ali_APP_ID, Ali_APP_PRIVATE_KEY);

                var response = await _aopClient.PageExecuteAsync(aliRequest);

                return response.Body;
            }
            return "";
        }

        /// <summary>
        /// 支付同步回调
        /// </summary>
        [HttpGet, AllowAnonymous]
        public IActionResult AliReturn()
        {
            /* 实际验证过程建议商户添加以下校验。
            1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
            */
            var ALIPAY_PUBLIC_KEY = m_Configuration["Aliyun:Pay:PublicKey"];

            Dictionary<string, string> sArray = GetRequestGet();
            if (sArray.Count != 0)
            {
                bool flag = AlipaySignature.RSACheckV2(sArray, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2", false);
                if (flag)
                {
                    var ordereNo = sArray["out_trade_no"];
                    // var order = await m_ProductOrderService.GetOrderByNo(ordereNo);
                    Console.WriteLine($"同步验证通过，订单号：{sArray["out_trade_no"]}");
                    ViewData["PayResult"] = "同步验证通过";
                }
                else
                {
                    Console.WriteLine($"同步验证失败，订单号：{sArray["out_trade_no"]}");
                    ViewData["PayResult"] = "同步验证失败";
                }
            }
            return Redirect("~/User/Index");
        }

        [HttpPost, AllowAnonymous]
        public async Task AliNotify()
        {
            /* 实际验证过程建议商户添加以下校验。
            1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
            */
            var ALIPAY_PUBLIC_KEY = m_Configuration["Aliyun:Pay:PublicKey"];
            Dictionary<string, string> sArray = GetRequestPost();

            LogHelper.Info("AliNotify", AlipaySignature.GetSignContent(sArray));
            if (sArray.Count != 0)
            {
                //     bool flag = AlipaySignature.RSA2Check(sArray, ALIPAY_PUBLIC_KEY);
                bool flag = AlipaySignature.RSACheckV2(sArray, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2", false);
                if (flag)
                {
                    //交易状态
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    try
                    {
                        var ordereNo = sArray["out_trade_no"];
                        var order = await m_ChargeService.GetOrderByNo(ordereNo);
                        if (order.OrderState == UOrderStatus.Complete || order.OrderState == UOrderStatus.PayOk)
                        {
                            await Response.WriteAsync("success");
                            return;
                        }

                        order.OrderState = UOrderStatus.PayOk;
                        order.TradeNo = sArray["trade_no"];
                        order.UpdateTime = DateTime.Now;
                        await m_ChargeService.Update(order);
                        await m_ChargeService.ProcessOrderAccount(order);

                        Console.WriteLine(Request.Form["trade_status"]);

                        await Response.WriteAsync("success");
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("AliNotify.Exception", ex.Message);
                        await Response.WriteAsync("fail");
                    }

                }
                else
                {
                    LogHelper.Error("AliNotify.Error", "签名校验失败");
                    await Response.WriteAsync("fail");
                }
            }
        }


        /// <summary>
        /// 支付同步回调
        /// </summary>
        [HttpGet, AllowAnonymous]
        public IActionResult AliReturnH5()
        {
            /* 实际验证过程建议商户添加以下校验。
            1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
            */
           var ALIPAY_PUBLIC_KEY = m_Configuration["Aliyun:PayH5:PublicKey"];


            Dictionary<string, string> sArray = GetRequestGet();
            if (sArray.Count != 0)
            {
                bool flag = AlipaySignature.RSACheckV2(sArray, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2", false);
                if (flag)
                {
                    var ordereNo = sArray["out_trade_no"];
                    // var order = await m_ProductOrderService.GetOrderByNo(ordereNo);
                    Console.WriteLine($"同步验证通过，订单号：{sArray["out_trade_no"]}");
                    ViewData["PayResult"] = "同步验证通过";
                }
                else
                {
                    Console.WriteLine($"同步验证失败，订单号：{sArray["out_trade_no"]}");
                    ViewData["PayResult"] = "同步验证失败";
                }
            }
            return Redirect("~/User/Index");
        }

        [HttpPost, AllowAnonymous]
        public async Task AliNotifyH5()
        {
            /* 实际验证过程建议商户添加以下校验。
            1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
            2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            4、验证app_id是否为该商户本身。
            */
           var ALIPAY_PUBLIC_KEY = m_Configuration["Aliyun:PayH5:PublicKey"];
            Dictionary<string, string> sArray = GetRequestPost();
            LogHelper.Info("AliNotify", AlipaySignature.GetSignContent(sArray));
            if (sArray.Count != 0)
            {
                //     bool flag = AlipaySignature.RSA2Check(sArray, ALIPAY_PUBLIC_KEY);
                bool flag = AlipaySignature.RSACheckV2(sArray, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2", false);
                if (flag)
                {
                    //交易状态
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    try
                    {
                        var ordereNo = sArray["out_trade_no"];
                        var order = await m_ChargeService.GetOrderByNo(ordereNo);
                        if (order.OrderState == UOrderStatus.Complete || order.OrderState == UOrderStatus.PayOk)
                        {
                            await Response.WriteAsync("success");
                            return;
                        }


                        order.OrderState = UOrderStatus.PayOk;
                        order.TradeNo = sArray["trade_no"];
                        order.UpdateTime = DateTime.Now;
                        await m_ChargeService.Update(order);
                        await m_ChargeService.ProcessOrderAccount(order);

                        Console.WriteLine(Request.Form["trade_status"]);

                        await Response.WriteAsync("success");
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("AliNotify.Exception", ex.Message);
                        await Response.WriteAsync("fail");
                    }

                }
                else
                {
                    LogHelper.Error("AliNotify.Error", "签名校验失败");
                    await Response.WriteAsync("fail");
                }
            }
        }




        private Dictionary<string, string> GetRequestGet()
        {
            Dictionary<string, string> sArray = new Dictionary<string, string>();

            ICollection<string> requestItem = Request.Query.Keys;
            foreach (var item in requestItem)
            {
                sArray.Add(item, Request.Query[item]);

            }
            return sArray;

        }


        private Dictionary<string, string> GetRequestPost()
        {
            Dictionary<string, string> sArray = new Dictionary<string, string>();

            ICollection<string> requestItem = Request.Form.Keys;
            foreach (var item in requestItem)
            {
                sArray.Add(item, Request.Form[item]);

            }
            return sArray;

        }

        #endregion



        [HttpGet, UserAuth]
        public async Task<IActionResult> OnLine(int productId,string account)
        {
            var data= await m_agentService.OnLine(productId, account);
            
            return View(data.Data);
        }
    }
}
